EN
JavaScript - exec() vs match()
7
points
In this article, we would like to explain the difference between RegExp
exec()
and String
match()
functions in JavaScript.
Differences:
expression.exec(text) | text.match(expression) |
located in e.g.
|
located in string, e.g.
|
shifts expression.lastIndex in some modes,e.g. in global mode ( g flag) | do not shifts expression.lastIndex ,e.g. match() call ignores the above property |
supports groups, e.g. we can use ( ) in the expressions |
do not support groups, |
returns single match with details per exec() calle.g. details: index, text, etc. | returns array with matched texts |
|
Practical examples
Example 1:
// ONLINE-RUNNER:browser;
// match() vs exec()
const expression = /\s/g;
const text = 'Example text.';
// match()
if (text.match(expression)) {
console.log('The string contains space(s).');
}
// exec()
expression.lastIndex = 0; // needed when we work with different textson the same expression object
// reasone: exec() shifts lastIndex value
if (expression.exec(text)) {
console.log('The string contains space(s).');
}
Example 2:
// ONLINE-RUNNER:browser;
// match() vs exec()
const expression = /\s/g;
const text = 'Example text with multiple spaces.';
// match()
const matches = text.match(expression);
if (matches) {
console.log('The string contains ' + matches.length + ' space(s).');
}
// exec()
expression.lastIndex = 0; // needed when we work with different textson the same expression object
// reasone: exec() shifts lastIndex value
while (true) {
const match = expression.exec(text);
if (match == null) {
break;
}
console.log('The string contains space (index=' + match.index + ').');
}