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+ 次瀏覽

啟動您的職業生涯

完成課程獲得認證

開始學習
廣告