JavaScript RegExp global Property
Last Updated : 05 Dec, 2024
Improve
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.
// 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);
- regex1 matches only the first occurrence of "test."
- regex2 matches all occurrences of "test" in the input string.
Syntax:
regex.global
Key Points
- Read-Only: The global property is a read-only boolean that reflects whether the g flag is set.
- Multiple Matches: Allows retrieval of all matches within a string.
- Stateful Matching: In conjunction with methods like exec(), the g flag tracks the position of the last match using the lastIndex property.
Real-World Examples of the global Property
1. Retrieving All Matches
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
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
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.
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
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?
- Complete Matching: Essential for tasks where multiple matches need to be found and processed.
- Efficient Parsing: Useful for extracting or manipulating repetitive patterns in strings.
- Versatile Applications: Often used in tasks like data processing, validation, and search-and-replace operations.
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:
- JavaScript RegExp Complete Reference
- Javascript Cheat Sheet-A Basic guide to JavaScript
- JavaScript Tutorial