JsRegex學習之test和compile的簡單介紹

來源:互聯網
上載者:User

標籤:style   class   blog   code   java   color   

RegExp 對象用於規定在文本中檢索的內容。

定義 RegExp

RegExp 對象用於儲存檢索模式。

通過 new 關鍵詞來定義 RegExp 對象。以下代碼定義了名為 patt1 的 RegExp 對象,其模式是 "e":

test方法如下

var patt1=new RegExp("e");RegExp 對象有 3 個方法:test()、exec() 以及 compile()。patt1.test("the best things in life are free")結果:truepatt1.test("x");結果:falsevar patt2=/e/patt2.test("ee")truevar patt2="/e/";patt2"/e/"patt2.test("xxx");TypeError: undefined is not a function從上述中看出,"/e/"和/e/區別太大了,前者只是一個字串,而後者是一個Regex對象,即RegExp對象

  

compile方法如下

compile() 方法用於改變 RegExp。compile() 既可以改變檢索模式,也可以添加或刪除第二個參數。var patt1=new RegExp("e");console.log(patt1.test("The best things in life are free"));patt1.compile("d");console.log(patt1.test("The best things in life are free"));由於字串中存在 "e",而沒有 "d",以上代碼的輸出是:true false

 

總結:上面的簡單介紹,只是解決怎樣用test和compile的問題

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.