Open In App

What is the Role of Global RegExp in JavaScript ?

Last Updated : 24 Apr, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

A global regular expression (RegExp) is a type of regular expression that can match all occurrences of a pattern in a string, not just the first occurrence. It can be used in JavaScript to search for patterns in texts with the help of the global flag (g) at the end of the actual regular expression itself, so essentially this global flag (g) allows you to use your pattern and then match, search, and replace text multiple times on a test string.

Syntax: To create a global regular expression, you can add the global flag g to a regular expression pattern using the following syntax:

var regex = /pattern/g;

Different approaches to use global regular expression in JavaScript:

1. match() method: This method returns an array of all matches of a pattern in a string. In this example, the match method will look for Geek in the test string and will return an array of all matches. The gi flags in the regular expression indicate that the replacement should be case-insensitive and global.

Javascript




var str = 'GeekforGeeks';
var regex = /Geek/gi;
var matches = str.match(regex);
console.log(matches); 


Output

[ 'Geek', 'Geek' ]

2. replace() method: This method replaces all occurrences of a pattern in a string with a new value. In this example, the “to” pattern will be replaced with the “for” which will result in the output GeekforGeeks. The gi flags in the regular expression indicate that the replacement should be case-insensitive and global.

Javascript




var str = 'GeektoGeeks';
var regex = /to/gi;
var newStr = str.replace(regex, 'for');
console.log(newStr);


Output

GeekforGeeks

Example 1: Removing all non-alphanumeric characters from a string

In this example, we’re using the replace() method and the regular expression [^a-z0-9\s] to remove all non-alphanumeric characters if they match any character that is not a letter, number, or whitespace character in a string. The gi flags in the regular expression indicate that the replacement should be case-insensitive and global.

Javascript




var str = '$GeekforGeeks!';
var regex = /[^a-z0-9\s]/gi;
var newStr = str.replace(regex, '');
console.log(newStr);


Output

GeekforGeeks

Example 2: Counting all occurrences of a pattern in a string

In this example, we’re using the match() method to find all occurrences of the word ‘the’ in a string, regardless of the case of the letter. The gi flags in the regular expression indicate that the replacement should be case-insensitive and global.

Javascript




var str = 'GeekforGeeks is a learning platform for geeks';
var regex = /geek/gi;
var count = (str.match(regex) || []).length;
console.log(count);


Output

3


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads