Reference to JavaScript matchAll method ES10/2019

JavaScript , , , , 0 Comments

We can use JavaScript matchAll method on any string and it returns all the matching results as an iterator that works easily with for...of loops and has properties like index, input and groups. It will return an empty iterator object if nothing matched.

Simple Example

const regex = /t(e)(st(\d?))/g;
const string = 'test1test2';
const matches = string.matchAll(regex);
for (const match of matches) {
  console.log(match);
}
// ["test1", "e", "st1", "1", index: 0, input: "test1test2", groups: undefined]
// ["test2", "e", "st2", "2", index: 5, input: "test1test2", groups: undefined]

As I said before JavaScript matchAll method will return an iterator of each match with properties like index, input and groups as shown below:

["test1", "e", "st1", "1", index: 0, input: "test1test2", groups: undefined]
["test2", "e", "st2", "2", index: 5, input: "test1test2", groups: undefined]

Syntax

myStr.matchAll(regexp)

Parameters

It receives only one parameter regexp. A regular expression object. If you pass the non-RegExp object, It will automatically convert it to a RegExp by using new RegExp(obj).

Additional properties

1. index:- The index of the first result found in the original string.

2. input:- A complete copy of original string.

3. groups:- It contained the result of any named capturing groups or will return undefined if no named capturing groups were defined.

Without Iterator Example

With the below example you can get a simple array as a result.

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

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

console.log(array[0]);
// expected output: 
// ["test1", "e", "st1", "1", index: 0, input: "test1test2", groups: undefined]

console.log(array[1]);
// expected output: 
// ["test2", "e", "st2", "2", index: 5, input: "test1test2", groups: undefined]

In the above example, we used object destructuring to create an array from an iterator. to read more about object destructuring:- JavaScript Destructuring ES6: The Complete Guide

For more MDN

That’s all I have got, I hope you understood, If I have missed anything else please let me know. Share it with love.

JavaScript matchAll method buginit.com
Spread the love
  • 1
    Share

Leave a Reply

avatar
  Subscribe  
Notify of