天天看點

RegExp 對象

什麼是 RegExp?

RegExp 是正規表達式的縮寫。

當您檢索某個文本時,可以使用一種模式來描述要檢索的内容。RegExp 就是這種模式。

簡單的模式可以是一個單獨的字元。

更複雜的模式包括了更多的字元,并可用于解析、格式檢查、替換等等。

您可以規定字元串中的檢索位置,以及要檢索的字元類型,等等。

定義 RegExp

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

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

var patt1=new RegExp("e");

當您使用該 RegExp 對象在一個字元串中檢索時,将尋找的是字元 "e"。

RegExp 對象的方法

RegExp 對象有 3 個方法:test()、exec() 以及 compile()。

test()

test() 方法檢索字元串中的指定值。傳回值是 true 或 false。

例子:

var patt1=new RegExp("e");

document.write(patt1.test("The best things in life are free"));

由于該字元串中存在字母 "e",以上代碼的輸出将是:

true

​​TIY​​

exec()

exec() 方法檢索字元串中的指定值。傳回值是被找到的值。如果沒有發現比對,則傳回 null。

例子 1:

var patt1=new RegExp("e");

document.write(patt1.exec("The best things in life are free"));

由于該字元串中存在字母 "e",以上代碼的輸出将是:

e

​​TIY​​

例子 2:

您可以向 RegExp 對象添加第二個參數,以設定檢索。例如,如果需要找到所有某個字元的所有存在,則可以使用 "g" 參數 ("global")。

如需關于如何修改搜尋模式的完整資訊,請通路我們的 ​​RegExp 對象參考手冊​​。

在使用 "g" 參數時,exec() 的工作原理如下:

  • 找到第一個 "e",并存儲其位置
  • 如果再次運作 exec(),則從存儲的位置開始檢索,并找到下一個 "e",并存儲其位置

var patt1=new RegExp("e","g");

do

{

result=patt1.exec("The best things in life are free");

document.write(result);

}

while (result!=null)

由于這個字元串中 6 個 "e" 字母,代碼的輸出将是:

eeeeeenull

​​TIY​​

compile()

compile() 方法用于改變 RegExp。

compile() 既可以改變檢索模式,也可以添加或删除第二個參數。

例子:

var patt1=new RegExp("e");

document.write(patt1.test("The best things in life are free"));

patt1.compile("d");

document.write(patt1.test("The best things in life are free"));      

由于字元串中存在 "e",而沒有 "d",以上代碼的輸出是:

truefalse