How to Match Multiple Occurrences With Regex in JavaScript

Tahseen Tauseef Feb 02, 2024
  1. Regular Expressions in JavaScript
  2. Use RegExp.prototype.exec() to Match Multiple Occurrences With Regex in JavaScript
  3. Use String.prototype.search() to Match Multiple Occurrences With Regex in JavaScript
  4. Use String.prototype.matchAll() to Match Multiple Occurrences With Regex in JavaScript
How to Match Multiple Occurrences With Regex in JavaScript

In this article, you will be learning about regular expressions in JavaScript and how you can match multiple occurrences in JavaScript.

Regular Expressions in JavaScript

Regular expressions are sequences of characters that produce a search pattern. While searching for data in a text, you may use this search pattern to communicate what you’re looking for.

A regular expression might be as basic as a single letter or as complicated as a whole pattern. Regular expressions may be used to do text search or text replacement operations.

Regular expressions have the potential to improve the power of your search significantly.

Use RegExp.prototype.exec() to Match Multiple Occurrences With Regex in JavaScript

The exec() function searches for a match in a given string.

Syntax:

exec(str)

Parameters:

  • str: The string against which you have to match the regular expression.

Return value:

  • If the match is successful, the exec() function returns an array and modifies the regular expression object’s lastIndex property. The matched text is the first item in the returned array, followed by one item for each parenthetical capture group of the matched text.
  • If the match is unsuccessful, the exec() function returns null and changes lastIndex to 0.

When the global or sticky flags are set on JavaScript RegExp objects, they are stateful. They save the previous match’s lastIndex.

Internally, exec() may be used to iterate through multiple matches in a text string (with capture groups).

Example:

const regex1 = RegExp('hello*', 'g');
const str1 = 'table hello, hello world';
let array1;

while ((array1 = regex1.exec(str1)) !== null) {
  console.log(`Found ${array1[0]}. Next starts at ${regex1.lastIndex}.`);
}

Output:

"Found hello. Next starts at 11."
"Found hello. Next starts at 18."

You can also access the above code segment through this link.

Specify the g Flag to Find Successive Matches

If you specify the g flag in your regular expression, you may often use the exec() function to discover subsequent matches in the exact text.

The search begins at the substring of str provided by the regular expression’s lastIndex property (test() advances the lastIndex property).

When looking for a different text, the lastIndex property will not be reset; instead, the search will begin at the current lastIndex.

Example:

let myRe = /ab*/g;
let str = 'abbcdefabh';
let myArray;
while ((myArray = myRe.exec(str)) !== null) {
  let msg = 'Found ' + myArray[0] + '. ';
  msg += 'Next match starts at ' + myRe.lastIndex;
  console.log(msg);
}

Output:

"Found abb. Next match starts at 3"
"Found ab. Next match starts at 9"

You can access the demo of the above code segment through this link.

Use exec() With RegEx Literals

You can also use exec() without explicitly creating a RegExp object.

Example:

let matches = /(hello \S+)/.exec('This is a hello world!');
console.log(matches[1]);

Output:

"hello world!"

You can access the demo of the above code segment through this link.

Use String.prototype.search() to Match Multiple Occurrences With Regex in JavaScript

The search() method finishes a search for a match between a regular expression and this String object.

Syntax:

search(regexp)

Parameters:

  • regexp: It is a regular expression object. If a non-RegEx object regexp is executed, it is implicitly converted to a RegExp with new RegExp(regexp).

Return value:

  • If a match is found, it will return the index of the first match between the regular expression and the provided string, or -1 if no match is found.

Example:

const paragraph =
    'The swift brown fox leaps over the sluggish dog. Was the dog truly sluggish if it barked??';

const regex = /[^\w\s]/g;

console.log(paragraph.search(regex));

console.log(paragraph[paragraph.search(regex)]);

Output:

43
"."

You can access the demo of the above code segment through this link.

Use String.prototype.matchAll() to Match Multiple Occurrences With Regex in JavaScript

The matchAll() function gives an iterator of all results matching a string against a regular expression. This includes capturing groups.

Syntax:

matchAll(regexp)

Parameters:

  • regexp: It is an object with regular expressions.

    When a non-RegEx object obj is given, it is implicitly turned to a RegExp using new RegExp(obj). A TypeError will be issued if the RegExp object does not have the /g flag.

Return value:

  • It will return an iterator (which is not a restartable iterable) of matches.
  • Each match is an array (with extra properties index and input). The match array has the matched text as the first item and then one thing for each parenthetical capture group of the matched text.

Example 1:

const regexp = /t(e)(st(\d?))/g;
const str = 'test1test2';

const array = [...str.matchAll(regexp)];

console.log(array[0]);

console.log(array[1]);

Output:

["test1", "e", "st1", "1"]
["test2", "e", "st2", "2"]

You can access the demo of the above code segment through this link.

Example 2:

function checkMultipleOccurrences(sentence) {
  var matchExpression = /(JavaScript?[^\s]+)|(typescript?[^\s]+)/g;
  return sentence.match(matchExpression);
}
var sentence =
    'This is my first JavaScript Program which is the subset of typescript';
console.log(sentence);
console.log(checkMultipleOccurrences(sentence));

Output:

"This is my first JavaScript Program which is the subset of typescript"
["JavaScript", "typescript"]

You can access the demo of the above code segment through this link.

To run the code mentioned above, use the following command:

node fileName.js.

Related Article - JavaScript Regex