How to test and execute a regular expression in JavaScript?

JavascriptWeb DevelopmentObject Oriented Programming

Following is the code for testing and executing a regular expression 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;
   .result,.sample {
      font-size: 20px;
      font-weight: 500;
<h1>Testing and executing regular expressions</h1>
<div class="sample"></div>
<div style="color: green;" class="result"></div>
<button class="Btn">CLICK HERE</button>
Click on the above button to test and execute the regular expression
   let sampleEle=document.querySelector('.sample');
   let resEle = document.querySelector('.result');
   let str = 'Hello world. This is a beautiful world';
   sampleEle.innerHTML =str;
   let pattern = new RegExp("world");
   document.querySelector(".Btn").addEventListener("click", () => {
      resEle.innerHTML += 'pattern.test(str) = ' + pattern.test(str) + '<br>';
      resEle.innerHTML += 'pattern.exec(str) = ' + pattern.exec(str) + '<br>';


The above code will produce the following output −

On clicking the ‘CLICK HERE’ button −

Published on 15-Jul-2020 17:37:16