1. 程式人生 > >js字串常用處理函式

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"