標籤:style blog http color os io java ar for
String類型
1.字串的模式比對方法
1) match(),與RegExp的exec()方法相同,也只接受一個參數,要麼是一個Regex,要麼是一個RegExp對象。
var text = "cat,bat,fat,sat";var pattern = /.at/;var matches = text.match(pattern);alert(matches[0]); //catalert(matches.index); //0alert(pattern.lastIndex); //0
2) search(),從字串開頭向後尋找模式,返回字串中第一個匹配項的索引,如果沒有則返回-1
var text = "cat,bat,fat,sat";var pattern = /at/;var pos = text.search(pattern);alert(pos); //1 ;第一個匹配的位置
3) replace() ,替換子字串的操作函數
var text = "cat,bat,fat,sat";var resultReplace = text.replace("at","ond");alert(resultReplace); //cond,bat,fat,sat resultReplace = text.replace(/at/g,"ond");alert(resultReplace); //cond,bond,fond,sond
ps:如果第一個參數是字串,那麼只會替換第一個子字串。要想替換說有子字串,唯一的辦法就是提供一個Regex,而且要指定全域(g)標誌。
- replace()方法的第二個參數也可以是一個函數。
例如:轉義HTML代碼中的< 、> 、“ 和 &
var pattern = /[<>"&]/g;function htmlEscape(text){ return text.replace(pattern,function(match,pos,originalText){ switch(match){ case "<": return "<"; case ">": return ">"; case "\"": return """; case "&": return "&"; } });} var text = "<p class=\"paraBg\">Hello Word!</p>" ;alert(htmlEscape(text));
4) split()方法,基於指定的分隔字元將一個字串分割成多個子串,並將結果放在一個數組中。第二個參數可用於指定數組的大小。
var url = "http://item.taobao.com/item.htm?a=1&b=2&c&d=xxx&e";var result = url.split("?");var re = result[1]; alert(re);//a=1&b=2&c&d=xxx&evar r = re.split("&");for(var i=0;i<r.length;i++){ alert(r[i]);}
5)fromCharCode()方法 與 charCodeAt()執行的是相反的操作。
fromCharCode()方法接收一或多個字元編碼,然後將它們轉化成一個字串。
alert(String.fromCharCode(65,66,101)); //ABe
JavaScript學習筆記(五)--- String類型