Explain JavaScript Regular Expression modifiers with examples

JavascriptWeb DevelopmentObject Oriented Programming

The JavaScript regular expression modifiers are optional part of a regular expression and allow us to perform case insensitive and global searchers. The modifiers can also be combined together.

Following are the modifiers −

ModifierDescription
gIt enables global matching and returns all the matched results instead of stopping at first match
iIt enables case insensitive matching
mIt enables multiline matching

Example

Following is the code for strict comparison in JavaScript switch statement −

 Live Demo

<!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 {
      font-size: 20px;
      font-weight: 500;
   }
</style>
</head>
<body>
<h1>JavaScript Regular expression modifiers</h1>
<div class="sample"></div>
<div style="color: green;" class="result"></div>
<button class="Btn">CLICK HERE</button>
<h3>
Click on the above button to see the modifiers operate on the above string
</h3>
<script>
   let sampleEle=document.querySelector('.sample');
   let resEle = document.querySelector('.result');
   let str = '\nHello world. This is a beautiful world';
   sampleEle.innerHTML =str;
   document.querySelector(".Btn").addEventListener("click", () => {
      resEle.innerHTML += '/^Hello/m = ' + str.match(/^Hello/m) + '<br>';
      resEle.innerHTML += '/world/g = ' + str.match(/world/g) + '<br>';
      resEle.innerHTML += '/WORLD/i = ' + str.match(/WORLD/i) + '<br>';
   });
</script>
</body>
</html>

Output

The above code will produce the following output −

On clicking the ‘CLICK HERE’ button −

raja
Published on 15-Jul-2020 17:34:15
Advertisements