Languages
[Edit]
EN

JavaScript - exec() vs match()

7 points
Created by:
Zayyan-Todd
560

In this article, we would like to explain the difference between exec() and 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';

// sometimes needed: expression.lastindex = 0;
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 sometimes it is needed to reset lastIndex reset before the exec() call
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

 

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 before use (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 before use (exec() shifts lastIndex value)

while (true) {
	const match = expression.exec(text);
	if (match) {
		console.log('The string contains space (index=' + match.index + ').');
	} else {
		break;
	}
}

 

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