exec() regex 方法在 JavaScript 中有什麼用?


exec()

exec() 方法是 regex 方法。 它搜尋字串以查詢指定的模式,並且與 test() regex 方法不同,它將找到的文字作為物件返回。如果未找到匹配項,則會將 null 作為輸出返回。我們來詳細討論一下。

示例 1

在以下示例中,透過 exec() 方法檢查了變數模式“est”。exec() regex 方法在整個文字中仔細檢查了給定的模式後,將模式作為 物件返回。

實際演示

<html>
<body>
<script>
   var obj = /est/.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 est and its position is 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

更新於: 30-07-2019

瀏覽量:72

開啟你的 職業生涯

完成課程並獲得認證

開始學習
廣告