目录
前言
JavaScript 字符串用于存储和操作文本,而字符串方法帮助您处理字符串。下面我对字符串的方法做一个大致的总结,有没提到的欢迎大家评论
字符串长度.length
length 属性返回字符串的长度:
var txt = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
var sln = txt.length;//26
查找字符串中的字符串indexOf()、lastIndexOf()、search()
indexOf() 方法返回字符串中指定文本首次出现的索引(位置):
var str = "The full name of China is the People's Republic of China.";
var pos = str.indexOf("China");//17 (包括空在内未找到返回-1)
indexOf()方法接受第二个参数作为检索起始位置的
lastIndexOf() 方法返回指定文本在字符串中最后一次出现的索引:
var str = "The full name of China is the People's Republic of China.";
var pos = str.lastIndexOf("China");//51 (包括空格在内未找到返回-1)
lastIndexOf()方法接受第二个参数作为检索起始位置的
search()方法搜索特定值的字符串,并返回匹配的位置:
var str = "The full name of China is the People's Republic of China.";
var pos = str.search("locate");//17 (他与infexOf方法很相似不同点是无法设置第二个开始位置参数)
提取部分字符串slice()、substring()
slice()提取字符串的某个部分并在新字符串中返回被提取的部分。
该方法设置两个参数:起始索引(开始位置),终止索引(结束位置)。
var str = "Apple, Banana, Mango";
var res = str.slice(7,13);//Banana (包括空在内)
如果省略第二个参数,则该方法将裁剪字符串的剩余部分
substring()substring() 类似于 slice()。
不同之处在于 substring() 无法接受负的索引。
var str = "Apple, Banana, Mango";
var res = str.substring(7,13);//Banana(包括空在内)
如果省略第二个参数,则该方法将裁剪字符串的剩余部分
substr()类似于 slice()。
不同之处在于第二个参数规定被提取部分的长度。
var str = "Apple, Banana, Mango";
var res = str.substr(7,3);//Ban(包括空在内)
如果省略第二个参数,则该 substr() 将裁剪字符串的剩余部分
替换字符串内容replace()
replace()方法用另一个值替换在字符串中指定的值:
str = "Please visit Microsoft!";
var n = str.replace("Microsoft", "W3School");//Please visit W3School
replace() 方法不会改变调用它的字符串。它返回的是新字符串。
默认地,replace() 只替换首个匹配:
如需执行大小写不敏感的替换,请使用正则表达式 /i
如需替换所有匹配,请使用正则表达式的 g 标志
转换为大写和小写toUpperCase()、toLowerCase()
toUpperCase()把字符串转换为大写:
var text1 = "Hello World!"; // 字符串
var text2 = text1.toUpperCase(); // text2 是被转换为大写的 text1
toLowerCase()
var text1 = "Hello World!"; // 字符串
var text2 = text1.toLowerCase(); // text2 是被转换为小写的 text1
连接两个或多个字符串concat()
concat()连接两个或多个字符串:
var text1 = "Hello";
var text2 = "World";
text3 = text1.concat(" ",text2);//Hello World!
concat() 方法可用于代替加运算符
删除字符串两端的空格trim()
trim()删除字符串两端的空格
var str = " Hello World! ";
alert(str.trim());//Hello World!
提取字符串字符charAt()、charCodeAt()
charAt()方法返回字符串中指定下标(位置)的字符串:
var str = "HELLO WORLD";
str.charAt(0); // 返回 H
charCodeAt()方法返回字符串中指定索引的字符 unicode 编码:
var str = "HELLO WORLD";
str.charCodeAt(0); // 返回 72
把字符串转换为数组split()
split()可以通过 split() 将字符串转换为数组:
var txt = "a,b,c,d,e"; // 字符串
txt.split(","); // 用逗号分隔
txt.split(" "); // 用空格分隔
txt.split("|"); // 用竖线分隔
可以通过这个借用数组方法反转字符串