test 方法

傳回的布林值 (Boolean) 將說明所搜尋的字串中是否有規則運算式模式存在。

function test(str : String) : Boolean

引數

  • str
    必要項。 用來執行搜尋的字串。

備註

test 方法會檢查字串中是否有模式存在,若有則傳回 true,否則傳回 false。 如果找到符合的項目,全域 RegExp 物件的屬性 (Property) 便會更新,以反映該符合項目的結果。

如果規則運算式已經設定了全域旗標,test 將會從 lastIndex 值表示的位置開始搜尋字串。 如果未設定全域旗標,則 test 會略過 lastIndex 值,並從字串之首開始搜尋。

範例

以下範例說明如何使用 test 方法。 若要使用以下範例,請將規則運算式模式及字串提供給函式。 此函式則會測試字串中是否出現該規則運算式模式,然後傳回說明搜尋結果的字串:

function TestDemo(re, teststring)
{
    // Test string for existence of regular expression.
    var found = re.test(teststring)

    // Format the output.
    var s = "";
    s += "'" + teststring + "'"

    if (found)
        s += " contains ";
    else
        s += " does not contain ";  
      
    s += "'" + re.source + "'"
    return(s);
}

需求

版本 3

套用至:

規則運算式物件

請參閱

參考

RegExp 物件

概念

規則運算式語法