JavaScript RegExp.test() 方法测试给定字符串是否与正则表达式定义的指定模式匹配。如果找到匹配项,则返回布尔值 'true';否则,它将返回 'false' 值。
在 JavaScript 中,正则表达式 (RegExp) 是一个对象,用于描述用于定义搜索模式的字符序列。
语法
以下是 JavaScript RegExp.test() 方法的语法 -
RegExp.test(str)
参数
此方法接受一个名为 'str' 的参数,如下所述 -
- str − 我们要在其中搜索匹配项的字符串。
返回值
如果在正则表达式和字符串之间找到匹配项,则此方法返回 'true',否则返回 'false'。
例子
如果找到匹配项,它将返回 'true'。
示例 1
在下面的程序中,我们使用 JavaScript RegExp.test() 方法来测试字符串是否与此字符串 “Hello World” 中的正则表达式定义的指定模式 (“\Hello*”) 匹配。
<html>
<head>
<title>JavaScript RegExp.test() Method</title>
</head>
<body>
<script>
const str = "Hello World";
const regex = new RegExp("\Hello*");
document.write("The given string: ", str);
document.write("<br>The regex: ", regex);
let bool = regex.test(str);
document.write("<br>Does the match found? ", bool);
</script>
</body>
</html>
输出
上面的程序返回 'true'。
The given string: Hello World
The regex: /Hello*/
Does the match found? true
The regex: /Hello*/
Does the match found? true
示例 2
如果未找到匹配项,它将返回 'false'。
以下是 JavaScript RegExp.test() 方法的另一个示例。我们使用此方法来测试字符串是否与此字符串 “JavaScript Regular Expression” 中的正则表达式定义的指定模式 (“\html*”, 'g') 匹配。
<html>
<head>
<title>JavaScript RegExp.test() Method</title>
</head>
<body>
<script>
const str = "JavaScript Regular Expression";
const regex = new RegExp("\html*", 'g');
document.write("The given string: ", str);
document.write("<br>The regex: ", regex);
let bool = regex.test(str);
document.write("<br>Does the match found? ", bool);
</script>
</body>
</html>
输出
执行上述程序后,它将返回 'false'。
The given string: JavaScript Regular Expression
The regex: /html*/g
Does the match found? false
The regex: /html*/g
Does the match found? false
示例 3
在带有全局标志 “g” 的正则表达式上使用 RegExp.test() 方法。
在下面的示例中,我们使用 JavaScript RegExp.test() 方法来测试手机号码 “8429618353” 和 “9511277492s” 是否有效。
<html>
<head>
<title>JavaScript RegExp.test() Method</title>
</head>
<body>
<script>
const mob1 = "8429618353";
const mob2 = "9511277492s";
var regex = new RegExp("^[0-9]{10}$", "g");
document.write("The given mobile numbers are : ", mob1 , " and ", mob2);
document.write("<br>The regex: ", regex);
let bool1 = regex.test(mob1);
let bool2 = regex.test(mob2);
document.write("<br>Does mobile number ", mob1, " is valid? ", bool1);
document.write("<br>Does mobile number ", mob2, " is valid? ", bool2);
</script>
</body>
</html>
输出
执行上述程序后,将显示以下语句 -
The given mobile numbers are : 8429618353 and 9511277492s
The regex: /^[0-9]{10}$/
Does mobile number 8429618353 is valid? true
Does mobile number 9511277492s is valid? false
The regex: /^[0-9]{10}$/
Does mobile number 8429618353 is valid? true
Does mobile number 9511277492s is valid? false