Skip to main content

test()

test()

test() 方法执行一个检索,用来查看正则表达式与指定的字符串是否匹配。返回 true 或 false。

快速上手

const str = "table football";

const regex = new RegExp("foo*");
const globalRegex = new RegExp("foo*", "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

语法

regexObj.test(str);

参数

str:用来与正则表达式匹配的字符串

返回值

如果正则表达式与指定的字符串匹配 ,返回 true;否则 false。

示例

使用 test()

一个简单的例子,测试 "hello" 是否包含在字符串的最开始,返回布尔值。

let str = "hello world!";
let result = /^hello/.test(str);
console.log(result);
// true