test 方法

返回一个布尔值,它指示在所搜索的字符串中是否存在正则表达式模式。

function test(str : String) : Boolean

实参

  • str
    必选。 将被执行搜索的字符串。

备注

test 方法检查字符串中是否存在某种模式,如果存在,则返回 true,否则将返回 false。 如果找到匹配项,则会更新全局 RegExp 对象的属性以反映匹配的结果。

如果为正则表达式设置了全局标志,则 testlastIndex 值指示的位置开始搜索字符串。 如果没有设置全局标志,则 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 对象

概念

正则表达式语法