JavaScript 中 exec() 正则表达式方法有什么用?

javascriptobject oriented programmingfront end technology

exec()

exec() 方法是一种 正则表达式方法。 它在字符串中搜索指定的模式,与 test() 正则表达式方法不同,它会将找到的文本作为对象返回。如果没有匹配项,它将给出 null 作为输出。让我们详细讨论一下。

示例 1

在下面的示例中,通过 exec() 方法检查变量模式"est"。 exec() 正则表达式方法在仔细检查整个文本中给定的模式后,将该模式作为 对象 返回。

<html>
<body>
<script>
var obj = /est/.exec("Tutorix is the best e-learning platform");
document.write(
"对象是 " + obj[0] + " 其位置为 " + obj.index);
</script>
</body>
</html>

输出

对象是 est,其位置为 16

示例 2

在下面的示例中,通过 exec() 方法检查变量模式"x"。exec() regex 方法在仔细检查整个文本中给定的模式后,将该模式作为对象返回。

<html>
<body>
<script>
   var obj = /x/.exec("Tutorix is the best e-learning platform");
   document.write(
   "The object is " + obj[0] + " and its position is " + obj.index);
</script>
</body>
</html>

输出

The object is x and its position is 6

相关文章