Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

JavaScript Regular Expression Modifiers Explained with Examples



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 −

Modifier Description
g It enables global matching and returns all the matched results instead of stopping at first match
i It enables case insensitive matching
m It 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 = '
Hello 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 −

Updated on: 2020-07-15T14:05:54+05:30

545 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements