RegExp.prototype.test()

Baseline 已广泛支持

此特性已相当成熟,可在许多设备和浏览器版本上使用。自 ⁨2015 年 7 月⁩以来,各浏览器均已提供此特性。

test() 方法是 RegExp 实例的一个方法,它使用该正则表达式来搜索匹配项,以确定一个正则表达式是否与指定的字符串匹配。如果匹配则返回 true;否则返回 false

当 JavaScript RegExp 对象设置了 globalsticky 标志(例如 /foo/g/foo/y)时,它们是有状态的。它们会存储上一次匹配的 lastIndextest() 利用这一点,可以用来遍历文本字符串中的多个匹配项(包括捕获组)。

试一试

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

语法

js
test(str)

参数

str

与正则表达式进行匹配的字符串。所有值都会被强制转换为字符串,因此省略此参数或传递 undefined 会导致 test() 搜索字符串 "undefined",这通常不是您想要的。

返回值

如果正则表达式与字符串 str 匹配,则为 true。否则为 false

描述

当您想知道字符串中是否存在某个模式时,请使用 test()test() 返回一个布尔值,这与 String.prototype.search() 方法不同(该方法返回匹配项的索引,如果没有找到则返回 -1)。

要获取更多信息(但执行速度较慢),请使用 exec() 方法。(这类似于 String.prototype.match() 方法。)

exec() 类似(或结合使用时),在同一个全局正则表达式实例上多次调用 test() 会跳过之前的匹配项。

示例

使用 test()

此示例测试字符串是否以 "hello" 开头,并返回布尔结果。

js
const str = "hello world!";
const result = /^hello/.test(str);

console.log(result); // true

以下示例会根据测试是否成功记录一条消息

js
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() 返回 truelastIndex 就不会重置——即使测试的是不同的字符串!

test() 返回 false 时,调用它的正则表达式的 lastIndex 属性会重置为 0

以下示例演示了这种行为

js
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

浏览器兼容性

另见