js字符串常用处理函数

我们以micro-major163字符串为例

1、charAt(索引值)  //查找具体的位置

"micro-major163".charAt(0);  //返回m

2、indexOf(searchValue[,fromIndex])    //返回索引位置,找不到时返回-1

"micro-major".indexOf("-");  //返回5
"micro-major-web".indexOf("-");  //返回5
"micro-major".indexOf("major");  //返回6,即查找字符串的第一个位置
"micromajor".indexOf("-");  //返回-1

3、search(regexp) 返回匹配的位置,找不到返回-1

"micromajor163".search(/[0-9]/);  //返回10
"micromajor163".search(/[A-Z]/);  //返回-1

4、match(regexp) 返回匹配到的字符,以数组形式返回;找不到返回null

"micromajor163".match(/[0-9]/);  //返回["1"]
"micromajor163".match(/[0-9]/g);  //返回["1","6","3"]
"micromajor163".match(/[A-Z]/);  //返回null

5、replace(regexp|substr,newSubstr)    //找到并替换成相应 的字符串

"micromajor163".replace("163","###");  //返回"micromajor###"
"micromajor163".replace(/[0-9]/,"#");  //返回"micromajor#63"
"micromajor163".replace(/[0-9]/g,"#");  //返回"micromajor###"
"micromajor163".replace(/[0-9]/g,"");  //返回"micromajor"

6、substring(indexA,indexB)   //字符串截取准确的字符,indexA首位置(包含),indexB末尾位置(不包含)

"micromajor".substring(5,7);  //返回"ma"
"micromajor".substring(5);  //返回"major"

7、slice(beginSlice,endSlice)  //字符串截取,首末位置,与subString()大同小异,然后不同的是可以传入负值(负值是从末尾数负数)

"micromajor".slice(5,7);  //返回"ma"
"micromajor".slice(5);  //返回"major"
"micromajor".slice(1,-1);  //返回"icromajo"
"micromajor".slice(-3);  //返回"jor"

8、substr(index,length)   //返回匹配的字符串

"micromajor".substr(5,2);  //返回"ma"
"micromajor".substr(5);  //返回"major"

9、slipt(separator[,limit])   //分隔符函数,以数组方式返回分隔后的字符串

"micro major".split(" ");  //返回["micro","major"]
"micro major".split(" ",1);  //返回["micro"]
"micro2major".split(/[0-9]/);  //返回["micro","major"]

10、toLowerCase()    //将所有的字符串都转换为小写字母

"MicroMajor".toLowerCase();   //返回"micromjaor"

11、toUpCase()    //将所有的字符串都转换成大写字母

"MicroMajor".toUpperCase();   //返回"MICROMAJOR"

12、String()   //转字符串

String(163);   //"163"
String(null);   //"null"

猜你喜欢

转载自blog.csdn.net/qq_41261490/article/details/81626201