標籤:
1、concat:字串、數組拼接返回新的字串、數組;
var a=‘hello,‘; var b=‘world!‘; document.write(a.concat(b)+‘<br>‘);//hello,world! var arr=[1,2,3,4]; var arr2=[5,6]; var c; c=arr.concat(arr2); alert(c instanceof Array);//true document.write(c+‘<br>‘);//1、2、3、4、5、6
2、indexOf、lastIndexOf:位置方法,接收兩個參數:要尋找的項和(此參數為可選)表示尋找起點位置的索引。
- indexOf:從數組開頭(索引0)向後尋找,找不到該項返回-1;
- lastIndexOf:從數組末尾向前尋找,找不到該項返回-1;
var numbers = [1,2,3,4,5,4,3,2,1];document.write(numbers.indexOf(4)+‘<br>‘); //3document.write(numbers.lastIndexOf(3)+‘<br>‘); //6document.write(numbers.indexOf(4, 4)+‘<br>‘); //5 從索引4往後尋找4得到其索引document.write(numbers.lastIndexOf(4, 4)+‘<br>‘); //3 從索引4往前尋找4得到其索引document.write(numbers.indexOf(6,2)+‘<br>‘);//-1
3、macth、exec:與Regex有關的匹配字串的函數,如果有匹配兩者都返回數組,無匹配都返回null。macth為字串方法match(regex);exec為Regex方法exec(string)
- Regex有分組(帶括弧)且沒有全域(g)屬性:兩者返回結果一致:
var str=‘boy,joy‘;var reg=/b(oy)/;document.write(reg.exec(str)+‘<br/>‘);//boy,oydocument.write(str.match(reg));//boy,oy
- Regex無分組且有全域屬性:由於全域屬性對exec無效,exec將返回只有一個元素的數組,該元素為Regex匹配的第一個串;match返回所有匹配。
var str=‘boy1,joy2‘;var reg=/oy\d/g;document.write(reg.exec(str)+‘<br/>‘);//oy1document.write(str.match(reg));//oy1,oy2
- Regex有分組且有全域屬性:match只返回全匹配,不返回分組匹配項;全域屬性對exec無效,先返回全匹配再返回分組匹配。
var str=‘boy,joy‘;var reg=/b(oy)/g;document.write(reg.exec(str)+‘<br/>‘);//boy,oydocument.write(str.match(reg));//boy
4、replace:字串替換,第一個參數為要替換的項(字串、Regex)。
var str="aba12cda34efa56";document.write(str.replace(/\d/g,"W")+"<br/>");//g替換所有匹配document.write(str.replace(/\d/,"W")+"<br/>");//只替換一次匹配document.write(str.replace(/\d$/,"W")+"<br/>");document.write(str.replace(‘a‘,‘A‘)+"<br/>");document.write(str.replace(/a/g,"A"));
5、slice、substr、substring:截取字串並返回新的字串。
substr(m,n)跟substring(m,n)的區別在於,前者從索引m開始截取n個長度,後者從索引m開始截取到索引n(不包括索引n位置的字元),截取長度為n-m。slice同substring
var str=‘helloworld‘; document.write(str.substr(1,5)+‘<br/>‘);//ellow document.write(str.substring(1,5)+‘<br/>‘);//ello document.write(str.slice(1,5)+‘<br/>‘);//ello //substr索引為負數的情況:末位字元索引為-1,類推,n>m的時候只截取到末位。 document.write(str.substr(-2,5)+‘<br>‘);//ld //substring索引為負數的情況:負數索引無效,以0替代。slice同 document.write(str.substring(-2,5)+‘<br>‘);//hello document.write(str.substring(-100,5));//hello
6、search:返回要尋找的字串索引,尋找不到返回-1。註:字串方法,對數組無效。
var str1="I am a programmer";document.write(str1.search(‘pro‘)+‘<br>‘);//7document.write(str1.search(/\s/));//1
7、split:以傳入的參數分割字串並返回數組。
var str1=‘abc-d‘;document.write(str1.split(‘‘)+‘<br>‘);//a,b,c,-,ddocument.write(str1.split(‘-‘)[1]);//d
8、length:返回字串的長度。
var str1=‘abc-d‘;var str2=‘hi,我是一名程式員!‘;document.write(str1.length+‘<br>‘);//5document.write(str2.length);//11
9、toLowerCase、toUpperCase:大小寫轉換。
var str1="I am a programmer";document.write(str1.toLowerCase()+‘<br>‘);//i am a programmerdocument.write(str1.toUpperCase());//I AM A PROGRAMMER
javascript 字串處理