1.定義:檢測某個文本時,可使用一種模式來描述要檢測的內容,RegExp就是這種模式。html
2.語法:var patt=new RegExp(pattern,modifiers);或var patt=/pattern/modifiers;函數
模式描述了一個表達式模型,修飾符描述了檢索是否全局,區分大小寫。this
3.RegExp修飾符,用於執行不區分大小寫的匹配。spa
在字符串中不區分大小寫找"W3CSchool"code
var str="Visit W3CSchool";
var patt1=/w3cschool/i;htm
如下標記的文本是得到的匹配的表達式:對象
Visit W3CSchool字符串
全文查找 "is"it
var str="Is this all there is?";
var patt1=/is/g;class
如下標記的文本是得到的匹配的表達式:
Is this all there is?
全文查找和不區分大小寫搜索 "is"
var str="Is this all there is?";
var patt1=/is/gi;
如下 標記的文本是得到的匹配的表達式:
Is this all there is?
test()方法搜索字符串指定的值,根據結果並返回真或假。
下面的示例是從字符串中搜索字符 "e" :
var patt1=new RegExp("e");
document.write(patt1.test("The best things in life are free"));
因爲該字符串中存在字母 "e",以上代碼的輸出將是:
true
當使用構造函數創造正則對象時,須要常規的字符轉義規則(在前面加反斜槓 \)
var re = new RegExp("\\w+");
exec() 方法檢索字符串中的指定值。返回值是被找到的值。若是沒有發現匹配,則返回 null。
下面的示例是從字符串中搜索字符 "e" :
var patt1=new RegExp("e");
document.write(patt1.exec("The best things in life are free"));
因爲該字符串中存在字母 "e",以上代碼的輸出將是:
e
複製複製:https://www.2cto.com/kf/201601/487274.html