JavaScript RegExp.exec() 方法用于在字符串中搜索正则表达式定义的指定模式。如果找到匹配项,它将返回一个包含匹配文本的数组,否则,它将在结果中返回 null。
在 JavaScript 中,正则表达式 (RegExp) 是一个对象,用于描述用于定义搜索模式的字符序列。正则表达式的最佳用途是表单验证。当用户通过表单(如输入字段)提交数据时,您可以应用正则表达式以确保数据满足特定条件。
语法
以下是 JavaScript RegExp.exec() 方法的语法 -
RegExp.exec(str)
参数
此方法接受一个名为 'str' 的参数,如下所述 -
- str − 需要搜索字符串。
返回值
此方法返回一个包含匹配文本 If a match is found 的数组。否则,它将返回 null 值。
例子
如果找到匹配项,此方法将返回包含匹配文本的数组。
示例 1
在以下示例中,我们使用 JavaScript RegExp.exec() 方法在字符串中搜索由字符串 “Qikepu Com” 中的正则表达式定义的模式 ('to*', 'g')。
<html>
<head>
<title>JavaScript RegExp.exec() 方法</title>
</head>
<body>
<script>
const regex = RegExp('ke*', 'u');
const str = "Qikepu Com";
document.write("要搜索的字符串: ", str);
document.write("<br>正则表达式: ", regex);
let arr = {};
arr = regex.exec(str);
document.write("<br>具有匹配文本的数组: ", arr);
document.write("<br>数组长度: ", arr.length);
</script>
</body>
</html>
输出
上面的程序返回一个包含匹配文本的数组。
要搜索的字符串: Qikepu Com
正则表达式: /ke*/u
具有匹配文本的数组: ke
数组长度: 1
正则表达式: /ke*/u
具有匹配文本的数组: ke
数组长度: 1
示例 2
如果未找到匹配项,该方法将返回 null。
以下是 JavaScript RegExp.exec() 方法的另一个示例。我们使用此方法在字符串中搜索由此字符串中的正则表达式 “Virat is a damn good batsman” 定义的模式 ('/mn\*', 'g')。
<html>
<head>
<title>JavaScript RegExp.exec() 方法</title>
</head>
<body>
<script>
const regex = RegExp('/mn\*', 'g');
const str = "Virat is a damn good batsman";
document.write("The string to be searched: ", str);
document.write("<br>The regex: ", regex);
let arr = {};
arr = regex.exec(str);
document.write("<br>An array with matched text: ", arr);
document.write("<br>The array length: ", arr.length);
</script>
</body>
</html>
输出
执行上述程序后,将返回 null。
The string to be searched: Virat is a damn good batsman
The regex: /\/mn*/g
An array with matched text: null
The regex: /\/mn*/g
An array with matched text: null
示例 3
我们可以在 conditional 语句中使用此方法的结果来检查是否找到匹配项。
<html>
<head>
<title>JavaScript RegExp.exec() Method</title>
</head>
<body>
<script>
const regex = RegExp('\llo*', 'g');
const str = "Hello World";
document.write("The string to be searched: ", str);
document.write("<br>The regex: ", regex);
let result = {};
result = regex.exec(str);
//using method result in conditional statement....
if(result != null){
document.write("<br>The string '" + result[0] + "' found.")
} else {
document.write("<br>Not found...");
}
</script>
</body>
</html>
输出
一旦执行了上述程序,它将根据条件返回一个语句 -
The string to be searched: Hello World
The regex: /llo*/g
The string 'llo' found.
The regex: /llo*/g
The string 'llo' found.