JS字符串详细操作
1.length
获取字符串长度
var str = "hello world";
str.length; //11
2.search()
search()
方法搜索特定值的字符串,并返回匹配的位置(如果不存在则返回-1)
var str = "hello world"; str.search("world"); //6 str.search("hi"); //-1
3.indexOf() 、 lastIndexOf()
indexOf()
返回字符串中一个子串第一次出现的索引(从左到右搜索)。如果没有匹配项,返回 -1
var str = "hello motor"; str.indexOf("hello"); //0 str.indexOf("hi"); //-1
lastIndexOf()
返回指定文本在字符串中最后一次出现的索引,如果没有匹配项,返回 -1
var str = "hello motor"; str.lastIndexOf("mo"); //6 str.lastIndexOf("hi"); //-1
两种方法都接受作为检索起始位置的第二个参数
var str = "abcdefabcdef"; str.indexOf("a"); //0 str.indexOf("a",1); //6 str.lastIndexOf("a"); //6 str.lastIndexOf("a",1); //0
4.slice()
提取字符串的某个部分,并在新字符串中返回被提取的部分slice(a,b) //注意:获取范围[a,b)
该方法设置两个参数:起始索引(开始位置 ),终止索引(结束位置)。可接受负的索引
var str = "one two three"; str.slice(4,7); //"two"
如果某个参数为负,则从字符串的结尾开始计数
var str = "one two three"; str.slice(4,-6); //"two"
str.slice(-9,-6); //"two"
如果省略第二个参数,则该方法将裁剪字符串的剩余部分
var str = "one two three"; str.slice(4); //"two three" str.slice(-5); //"three"
5.substring()
substring(start,end); //注意:截取字符串的范围是[start, end)
该方法设置两个参数:起始索引(开始位置),终止索引(结束位置)。无法接受负的索引
var str = "one two three"; str.substring(0,7); //"one two" str.substring(4); //"two three"
6.substr()
substr(a,b) //截取字符串,范围是从下标为a的字符开始,截取长度为b
该方法设置两个参数:起始索引(开始位置 可为负数),截取的长度。
var str = "one two three" str.substr(0,3); //"one" str.substr(-9,3); //"two" str.substr(4); //"two three"
7.replace()
用另一个值替换在字符串中指定的值,不会改变调用它的字符串。它返回的是新字符串。默认地,replace()
只替换首个匹配,并对大小写敏感
var str = "six SIX six"; str.replace("six","SIX"); //"SIX SIX six" str.replace("SIX","six"); //"six six six"
如需执行大小写不敏感的替换,请使用正则表达式 /i(大小写不敏感),如需替换所有匹配,请使用正则表达式的 g 标志(用于全局搜索)
var str = "six SIX Six"; str.replace(/six/ig,'6'); //"6 6 6"
8.toUpperCase()、toLowerCase()
toUpperCase()
把字符串转换为大写;toLowerCase()
把字符串转换为小写
var str= "Hello World!"; str.toUpperCase(); //"HELLO WORLD!" str.toLowerCase(); //"hello world!"
9.concat()
concat()
连接两个或多个字符串
var str1 = "Hello"; var str2= "World"; var str3= str1.concat(str2); // "HelloWorld" var str4 = str1.concat(" ",str2,"!"); //"Hello World!"
10.trim()
trim()
方法删除字符串两端的空白符
var str = " Hello World! "; str.trim(); // "Hello World!"
11.split()
可以通过 split()
将字符串转换为数组。可接受正则匹配
var str = "a,b,_c,d b"; str.split(''); //["a", ",", "b", ",", "_", "c", ",", "d", " ", "b"] str.split(','); //["a", "b", "_c", "d b"] str.split('_'); //["a,b,", "c,d b"] str.split(' '); //["a,b,_c,d", "b"] str.split(/,|\_|\s/g); //["a", "b", "", "c", "d", "b"]
12.str[idx]、charAt()、charCodeAt()
str[idx]
属性访问charAt()
方法返回字符串中指定下标(位置)的字符串charCodeAt()
方法返回字符串中指定索引的字符 unicode 编码
var str="one two three" str[0]; //"o" str.charAt(str.length-1); //e str[-2]; //undefined str.charAt(-2); //"" str.charCodeAt(0); //111