JavaScript RegExp g Modifier
- Previous page g
- Next Page i
- Go to the Previous Level JavaScript RegExp Reference Manual
Definition and usage
"g
" modifier specifies global matching.
Global matching finds all matches (compared to matching only the first one).
Instance
Example 1
Global search for "is":
let pattern = /is/g; let result = text.match(pattern);
Example 2
Use regular expression function exec():
let text = "Is this all there is?"; let pattern = /is/g; let result = pattern.exec(text);
Example 3
Use regular expression function test():
let pattern = /is/g; let result = pattern.test(text);
Example 4
Use string function match():
let pattern = /is/g; let result = text.match(pattern);
Syntax
new RegExp("regexp", "g")
Or abbreviated as:
/regexp/g
Hint
For global, case-insensitive search, please use "i" modifier Used with the g modifier.
Global, case-insensitive search for "is":
Example 1
Use regular expression function exec():
let text = "Is this all there is?"; let result = /is/gi.exec(text);
Example 2
Use regular expression function test():
let text = "Is this all there is?"; let result = /is/gi.test(text);
Example 3
Use string function match():
let text = "Is this all there is?"; let result = text.match(/is/gi);
Hint
You can use Global property Check if the g modifier is set.
let pattern = /W3S/g; let result = pattern.global;
Regular expression search methods
In JavaScript, text search using regular expressions can be completed with different methods.
UsagePattern (pattern)As regular expressions, these are the most commonly used methods:
Example | Description |
---|---|
text.match(pattern) | String method match() |
text.search(pattern) | String method search() |
pattern.exec(text) | RexExp method exec() |
pattern.test(text) | RexExp method test() |
Browser support
/regexp/g
Is ECMAScript1 (ES1) feature.
All browsers fully support ES1 (JavaScript 1997):
Chrome | IE | Edge | Firefox | Safari | Opera |
---|---|---|---|---|---|
Support | Support | Support | Support | Support | Support |
- Previous page g
- Next Page i
- Go to the Previous Level JavaScript RegExp Reference Manual