RegExp.prototype.test()
test() 方法是 实例的一个方法,它使用该正则表达式来搜索匹配项,以确定一个正则表达式是否与指定的字符串匹配。如果匹配则返回 RegExptrue;否则返回 false。
当 JavaScript 对象设置了 RegExpglobal 或 sticky 标志(例如 /foo/g 或 /foo/y)时,它们是有状态的。它们会存储上一次匹配的 lastIndex。test() 利用这一点,可以用来遍历文本字符串中的多个匹配项(包括捕获组)。
试一试
const str = "table football";
const regex = /fo+/;
const globalRegex = /fo+/g;
console.log(regex.test(str));
// Expected output: true
console.log(globalRegex.lastIndex);
// Expected output: 0
console.log(globalRegex.test(str));
// Expected output: true
console.log(globalRegex.lastIndex);
// Expected output: 9
console.log(globalRegex.test(str));
// Expected output: false
语法
test(str)
参数
返回值
如果正则表达式与字符串 str 匹配,则为 true。否则为 false。
描述
当您想知道字符串中是否存在某个模式时,请使用 test()。test() 返回一个布尔值,这与 String.prototype.search() 方法不同(该方法返回匹配项的索引,如果没有找到则返回 -1)。
要获取更多信息(但执行速度较慢),请使用 exec() 方法。(这类似于 String.prototype.match() 方法。)
与 exec() 类似(或结合使用时),在同一个全局正则表达式实例上多次调用 test() 会跳过之前的匹配项。
示例
使用 test()
此示例测试字符串是否以 "hello" 开头,并返回布尔结果。
const str = "hello world!";
const result = /^hello/.test(str);
console.log(result); // true
以下示例会根据测试是否成功记录一条消息
function testInput(re, str) {
const midString = re.test(str) ? "contains" : "does not contain";
console.log(`${str} ${midString} ${re.source}`);
}
在带有“global”标志的正则表达式上使用 test()
当正则表达式设置了 global 标志时,test() 会推进正则表达式的 lastIndex 属性。(RegExp.prototype.exec() 也会推进 lastIndex 属性。)
后续对 test(str) 的调用将从 lastIndex 开始继续搜索 str。每次 test() 返回 true 时,lastIndex 属性都会继续增加。
注意: 只要 test() 返回 true,lastIndex 就不会重置——即使测试的是不同的字符串!
当 test() 返回 false 时,调用它的正则表达式的 lastIndex 属性会重置为 0。
以下示例演示了这种行为
const regex = /foo/g; // the "global" flag is set
// regex.lastIndex is at 0
regex.test("foo"); // true
// regex.lastIndex is now at 3
regex.test("foo"); // false
// regex.lastIndex is at 0
regex.test("barfoo"); // true
// regex.lastIndex is at 6
regex.test("foobar"); // false
// regex.lastIndex is at 0
regex.test("foobarfoo"); // true
// regex.lastIndex is at 3
regex.test("foobarfoo"); // true
// regex.lastIndex is at 9
regex.test("foobarfoo"); // false
// regex.lastIndex is at 0
// (...and so on)
规范
| 规范 |
|---|
| ECMAScript® 2026 语言规范 # sec-regexp.prototype.test |
浏览器兼容性
加载中…