JavaScript 中 test() 方法的用途是什么?
test() 方法是一个正则表达式方法。它搜索字符串中的模式,并根据结果返回true或false。如果遇到给定的模式,则返回 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
广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP