test() 方法执行一个检索,用来查看正则表达式与指定的字符串是否匹配。返回 true 或 false。
regexObj.test(str)
str如果正则表达式与指定的字符串匹配 ,返回true;否则false。
当你想要知道一个模式是否存在于一个字符串中时,就可以使用 test()(类似于 String.prototype.search() 方法),差别在于test返回一个布尔值,而 search 返回索引(如果找到)或者-1(如果没找到);若想知道更多信息(然而执行比较慢),可使用exec() 方法(类似于 String.prototype.match() 方法)。 和 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 处开始匹配字符串,( 同样改变正则本身的 exec()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 |
| 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 8.0之前的版本 (Firefox 8.0 / Thunderbird 8.0 / SeaMonkey 2.5), test() 被不正确地实现了;当无参数地调用时,它会匹配之前的输入值 (RegExp.input 属性),而不是字符串"undefined"。这已经被修正了;现在 /undefined/.test() 正确地返回true,而不是错误。