JavaScript 中的 test() 方法有什么用?
javascriptobject oriented programmingfront end technology更新于 2025/6/5 10:52:17
test() 方法是一种 正则表达式 方法。它在字符串中搜索模式,并根据结果返回 true 或 false。如果遇到给定的模式,则返回 true,否则返回 false。它区分大小写。让我们详细讨论一下。
示例 1
在下面的例子中,给出了一个名为"Tutorix 是最好的电子学习平台"的文本,并检查模式"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
相关文章
有用资源
javascript 参考教程 - 该教程包含有关 javascript 的更多信息:https://www.cainiaomax.com/javascript/

