JavaScript RegExp g Modifier

The RegExp g Modifier in JavaScript is used to find all the occurrences of the pattern instead of stopping after the first match i.e it performs a global match. 

Syntax: 

/regexp/g 

or

new RegExp("regexp", "g")

Example 1: This example searches the word “Beginner” in the whole string. 

Javascript




function geek() {
    let str1 = "w3wiki is the computer "
        + "science portal for Beginner.";
    let regex4 = /Beginner/g;
    let match4 = str1.match(regex4);
 
    console.log("Found " + match4.length
        + " matches: " + match4);
}
geek()


Output

Found 3 matches: Beginner,Beginner,Beginner

Example 2: This example searches the word “portal” in the whole string and replaces it with “PORTAL”. 

Javascript




function geek() {
    let str1 = "w3wiki is the computer "
        + "science portal for Beginner.";
    let regex4 = new RegExp("portal", "g");
    let replace = "PORTAL";
    let match4 = str1.replace(regex4, replace);
    console.log(" New string: " + match4);
}
geek()


Output

 New string: w3wiki is the computer science PORTAL for Beginner.

Supported Browsers: The browsers supported by RegExp g Modifier are listed below:

  • Google Chrome
  • Apple Safari
  • Mozilla Firefox
  • Opera
  • Internet Explorer

We have a complete list of Javascript RegExp expressions, to check those please go through this JavaScript RegExp Complete Reference article.

We have a Cheat Sheet on Javascript where we covered all the important topics of Javascript to check those please go through Javascript Cheat Sheet-A Basic guide to JavaScript.  



Contact Us