使用 JavaScript 正則表示式迴圈匹配內容
以下程式碼用於在 Javascript 中迴圈並查詢正則表示式匹配 -
示例
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<style>
body {
font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
}
.result,
.sample {
font-size: 18px;
color: blueviolet;
font-weight: 500;
}
.sample {
color: red;
}
</style>
</head>
<body>
<h1>Looping over regex matches</h1>
<div class="sample">
There is a cat lying besides the cricket bat and chasing the rat
</div>
<div class="result"></div>
<button class="Btn">CLICK HERE</button>
<h3>Click on the above button to match words ending with 'at' in the above
sentence</h3>
<script>
let BtnEle = document.querySelector(".Btn");
let resEle = document.querySelector(".result");
let sampleEle = document.querySelector(".sample");
let text = sampleEle.innerHTML;
BtnEle.addEventListener("click", () => {
text.match(/at/g).forEach((element) => {
resEle.innerHTML += 'Found a match ending with "at" <br>';
});
});
</script>
</body>
</html>輸出

點選“點我”按鈕後 -

廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP