test 方法
更新:2007 年 11 月
傳回的布林值 (Boolean) 將說明所搜尋的字串中是否有規則運算式模式存在。
function test(str : String) : Boolean
引數
- str
必要項。用來執行搜尋的字串。
備註
test 方法會檢查字串中是否有模式存在,若有則傳回 true,否則傳回 false。如果找到符合的項目,全域 RegExp 物件的屬性 (Property) 便會更新,以反映該符合項目的結果。
如果規則運算式已經設定了全域旗標,test 將會從 lastIndex 值表示的位置開始搜尋字串。如果未設定全域旗標,則 test 會略過 lastIndex 值,並從字串之首開始搜尋。
範例
以下範例說明如何使用 test 方法。若要使用以下範例,請將規則運算式模式及字串提供給函式。此函式則會測試字串中是否出現該規則運算式模式,然後傳回說明搜尋結果的字串:
function TestDemo(re, s){
var s1; //Declare variable.
// Test string for existence of regular expression.
if (re.test(s)) //Test for existence.
s1 = " contains "; //s contains pattern.
else
s1 = " does not contain "; //s does not contain pattern.
return("'" + s + "'" + s1 + "'"+ re.source + "'"); //Return string.
}