test() 方法执行一个检索,用来查看正则表达式与指定的字符串是否匹配。返回 true 或 false。
语法
regexObj.test(str)
参数
-
str - 用来与正则表达式匹配的字符串
返回值
如果正则表达式与指定的字符串匹配 ,返回true;否则false。
描述
当你想要知道一个模式是否存在于一个字符串中时,就可以使用 test()(类似于 exec() (或者组合使用),一样,在相同的全局正则表达式实例上多次调用将会越过之前的匹配。test
示例
使用 test()
一个简单的例子,测试 "hello" 是否包含在字符串的最开始,返回布尔值。
let str = 'hello world!';
let result = /^hello/.test(str);
console.log(result);
// true
下例打印一条信息,该信息内容取决于是否成功通过指定测试:
function testinput(re, str){
var midstring;
if (re.test(str)) {
midstring = " contains ";
} else {
midstring = " does not contain ";
}
console.log(str + midstring + re.source);
}
当设置全局标志的正则使用test()
如果正则表达式设置了全局标志,test() 的执行会改变正则表达式 lastIndex属性。连续的执行test()方法,后续的执行将会从 lastIndex 处开始匹配字符串,(lastIndex属性值).
下面的实例表现了这种行为:
var regex = /foo/g;
// regex.lastIndex is at 0
regex.test('foo'); // true
// regex.lastIndex is now at 3
regex.test('foo'); // false
规范
| Specification | Status | Comment |
|---|---|---|
| ECMAScript 3rd Edition (ECMA-262) | Standard | Initial definition. Implemented in JavaScript 1.2. |
| ECMAScript 5.1 (ECMA-262) RegExp.test |
Standard | |
| ECMAScript 2015 (6th Edition, ECMA-262) RegExp.test |
Standard | |
| ECMAScript Latest Draft (ECMA-262) RegExp.test |
Draft |
浏览器兼容性
这个页面的兼容性表格是由结构数据生成。如果你想对数据作出贡献,详情请前往
https://github.com/mdn/browser-compat-data 并给我们一个PR。
Update compatibility data on GitHub
| Desktop | Mobile | Server | |||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
test |
Chrome Full support 1 | Edge Full support 12 | Firefox Full support 1 | IE Full support 4 | Opera Full support Yes | Safari Full support Yes | WebView Android Full support 1 | Chrome Android Full support 18 | Firefox Android Full support 4 | Opera Android Full support Yes | Safari iOS Full support Yes | Samsung Internet Android Full support 1.0 | nodejs Full support Yes |
Legend
- Full support
- Full support
Firefox特殊注意
在 Firefox 8之前, test() 被不正确地实现了;当无参数地调用时,它会匹配之前的输入值 (RegExp.input 属性),而不是字符串"undefined"。这已经被修正了;现在 /undefined/.test() 正确地返回true,而不是错误。