RegExp.prototype.test()
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
