JavaScript 中 test() 方法的用途是什么?


test() 方法是一个正则表达式方法。它搜索字符串中的模式,并根据结果返回truefalse。如果遇到给定的模式,则返回 true,否则返回 false。它是区分大小写的。让我们详细讨论一下。

示例 1

在下面的示例中,给定了一个名为“Tutorix is the best e-learning platform”的文本,并检查模式“Tu”是否存在。由于模式存在,test() 方法返回true作为输出。

在线演示

<html>
<body>
<p id="text">Tutorix is the best e-learning platform</p>
<p id="test"></p>
<script>
   var text = document.getElementById("text").innerHTML;
   document.getElementById("test").innerHTML = /Tu/.test(text);
</script>
</body>
</html>

输出

Tutorix is the best e-learning platform
true

示例 2

在下面的示例中,检查模式“tu”是否在提供的文本中。如果仔细观察文本,我们会发现存在“Tu”,但不存在“tu”。test() 方法甚至会检查大小写敏感性。因此,该方法的结果为false,并显示结果,如输出所示。

在线演示

<html>
<body>
<p id="text">Tutorix is the best e-learning platform</p>
<p id="test"></p>
<script>
   var text = document.getElementById("text").innerHTML;
   document.getElementById("test").innerHTML = /tu/.test(text);
</script>
</body>
</html>

输出

Tutorix is the best e-learning platform
false

更新于:2020年7月1日

1K+ 次浏览

启动您的职业生涯

完成课程获得认证

开始学习
广告
© . All rights reserved.