Looping over matches with JavaScript regular expressions

Following is the code for looping over regular expression matches in javaScript −


 Live Demo

<!DOCTYPE html>
<html lang="en">
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
   body {
      font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
   .sample {
      font-size: 18px;
      color: blueviolet;
      font-weight: 500;
   .sample {
      color: red;
<h1>Looping over regex matches</h1>
<div class="sample">
There is a cat lying besides the cricket bat and chasing the rat
<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
   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>';


On clicking the ‘CLICK HERE’ button −