JavaScript學習筆記(五)--- String類型

來源:互聯網
上載者:User

標籤: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 "&lt;";            case ">":                return "&gt;";            case "\"":                return "&quot";            case "&":                return "&amp";        }    });} 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類型

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.