A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://www.geeksforgeeks.org/javascript-regexp-global-property/ below:

JavaScript RegExp global Property - GeeksforGeeks

JavaScript RegExp global Property

Last Updated : 05 Aug, 2025

The global property in JavaScript regular expressions indicates whether the g (global) flag is enabled. A regular expression with the g flag searches for all matches in the input string rather than stopping after the first match.

JavaScript
// Regular expression without 'g' flag
let regex1 = /test/;
console.log(regex1.global); 

// Regular expression with 'g' flag
let regex2 = /test/g;
console.log(regex2.global); 
Syntax:
regex.global
Key Points Real-World Examples of the global Property 1. Retrieving All Matches JavaScript
let s = "cat dog cat";
let regex = /cat/g;

let matches = s.match(regex);
console.log(matches); 

The g flag ensures all occurrences of "cat" are captured.

2. Using exec() Iteratively JavaScript
let s = "hello hello world";
let regex = /hello/g;

let match;
while ((match = regex.exec(s)) !== null) {
    console.log(`Matched: ${match[0]} at index ${match.index}`);
}

The g flag allows exec() to iterate over all matches in the string.

3. Replacing All Matches JavaScript
let s = "red apple, red cherry, red berry";
let regex = /red/g;

let result = s.replace(regex, "green");
console.log(result); 

The g flag ensures all occurrences of "red" are replaced with "green."

4. Counting Matches

The g flag helps count the total number of numeric sequences.

JavaScript
let s = "123 456 789";
let regex = /\d+/g;

let count = 0;
while (regex.exec(s)) {
    count++;
}
console.log(`Number of matches: ${count}`); 
5. Splitting a String by a Pattern JavaScript
let s = "apple;banana;cherry";
let regex = /;/g;

let parts = s.split(regex);
console.log(parts); 

Output
[ 'apple', 'banana', 'cherry' ]

The g flag ensures the pattern matches all separators in the string.

Why Use the global Property? Conclusion

The global property is a cornerstone of JavaScript regular expressions, enabling comprehensive pattern matching for a wide range of real-world applications.

Recommended Links:

RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4