Related Articles

Related Articles

JavaScript | RegExp g Modifier
  • Last Updated : 22 Apr, 2019

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 global match.

Syntax:

/regexp/g 

or

new RegExp("regexp", "g")

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

filter_none

edit
close

play_arrow

link
brightness_4
code

<!DOCTYPE html>
<html>
  
<head>
    <title>
        JavaScript RegExp g Modifier
    </title>
</head>
  
<body style="text-align:center">
      
    <h1 style="color:green">
        GeeksforGeeks
    </h1>
      
    <h2>RegExp g Modifier</h2>
      
    <p>
        geeksforgeeks is the computer 
        science portal for geeks.
    </p>
      
    <button onclick="geek()">
        Click it!
    </button>
      
    <p id="app"></p>
      
    <script>
        function geek() {
        var str1 = "geeksforgeeks is the computer "
                 + "science portal for geeks.";
        var regex4 = /geeks/g;
        var match4 = str1.match(regex4);
  
        document.getElementById("app").innerHTML = 
                    "Found " + match4.length
                    + " matches: " + match4;
        }
    </script>
</body>
  
</html>                    

chevron_right


Output:
Before Clicking the button:
g
After Clicking the button:
g



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

filter_none

edit
close

play_arrow

link
brightness_4
code

<!DOCTYPE html>
<html>
  
<head>
    <title>
        JavaScript RegExp g Modifier
    </title>
</head>
  
<body style="text-align:center">
      
    <h1 style="color:green">
        GeeksforGeeks
    </h1>
      
    <h2>RegExp g Modifier</h2>
      
    <p>
        geeksforgeeks is the computer 
        science portal for geeks.
    </p>
      
    <button onclick="geek()">
        Click it!
    </button>
      
    <p id="app"></p>
      
    <script>
        function geek() {
        var str1 = "geeksforgeeks is the computer "
                 + "science portal for geeks.";
        var regex4 = new RegExp("portal", "g");         
        var replace = "PORTAL";
        var match4 = str1.replace(regex4, replace);
            document.getElementById("app").innerHTML = 
            " New string: " + match4;
        }
    </script>
</body>
  
</html>                    

chevron_right


Output:
Before Clicking the button:
g
After Clicking the button:
g

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

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

full-stack-img




My Personal Notes arrow_drop_up
Recommended Articles
Page :