Languages
[Edit]
EN

JavaScript - exec() vs match()

7 points
Created by:
Zayyan-Todd
860

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 RegExp class,

e.g.

const expression = /\s/g;
const text = 'a b c';

const match = expression.exec(text);

located in string,

e.g.

const expression = /\s/g;
const text = 'a b c';

const matches = text.match(expression);
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,
e.g. ( ) are ignored in the expressions

returns single match with details per exec() call
e.g. details: index, text, etc.
returns array with matched texts

Warning:

exec() method updates lastIndex property value, so sometimes, when we use the same expression with different texts it is needed to reset lastIndex property to start pattern matching sice text begining,

e.g. expression.lastIndex = 0 before exec() method call

 

 

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 + ').');
}
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join