Please note, this is a STATIC archive of website developer.mozilla.org from 03 Nov 2016, cach3.com does not collect or store any user information, there is no "phishing" involved.

RegExp.prototype.test()

概述

test() 方法执行一个检索,用来查看正则表达式与指定的字符串是否匹配。返回 truefalse

语法

regexObj.test(str)

参数

str
用来与正则表达式匹配的字符串

返回值

布尔值 true 或 false

描述

当你想要知道一个模式是否存在于一个字符串中时,就可以使用 test()(类似于 String.search。若想知道更多信息,可使用(执行比较慢) exec 方法(类似于 String.match 方法)。 As with exec (or in combination with it), test called multiple times on the same global regular expression instance will advance past the previous match.

示例

例子:使用 test

下例打印一条信息,该信息内容取决于是否成功通过指定测试:

function testinput(re, str){
    var midstring;
    if (re.test(str)) {
        midstring = " contains ";
    } else {
        midstring = " does not contain ";
    }
    console.log(str + midstring + re.source);
}

规范

Specification Status Comment
ECMAScript 3rd Edition. Implemented in JavaScript 1.2 Standard Initial definition.
ECMAScript 5.1 (ECMA-262)
RegExp.test
Standard  
ECMAScript 2015 (6th Edition, ECMA-262)
RegExp.test
Standard  

浏览器兼容性

Feature Chrome Firefox (Gecko) Internet Explorer Opera Safari
Basic support (Yes) (Yes) (Yes) (Yes) (Yes)
Feature Android Chrome for Android Firefox Mobile (Gecko) IE Mobile Opera Mobile Safari Mobile
Basic support (Yes) (Yes) (Yes) (Yes) (Yes) (Yes)

Gecko-specific notes

Prior to Gecko 8.0 (Firefox 8.0 / Thunderbird 8.0 / SeaMonkey 2.5), test() was implemented incorrectly; when it was called with no parameters, it would match against the value of the previous input (RegExp.input property) instead of against the string "undefined". This is fixed; now /undefined/.test() correctly results in true, instead of an error.

相关链接

文档标签和贡献者

 此页面的贡献者: teoli, AlexChao
 最后编辑者: teoli,