JS 正则表达式 test()
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](/api/js-es/ob-reg-exp/last-index.html "The lastIndex is a read/write integer property of regular expression instances that specifies the index at which to start the next match.")属性值
).
下面的实例表现了这种行为:
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 |
Firefox特殊注意
在 Firefox 8之前, test()
被不正确地实现了;当无参数地调用时,它会匹配之前的输入值 (RegExp.input 属性),而不是字符串"undefined"。这已经被修正了;现在 /undefined/.test()
正确地返回true
,而不是错误。