TypeScript String matchAll() Method
Last Updated :
21 Feb, 2024
In TypeScript, the matchAll() method of String values returns an iterator of all results matching the string against a regular expression, including capturing groups. The matchAll() method is quite similar to the match() method, but match() returns only the first match and it doesn’t include capturing groups.
Syntax:
string.matchAll(regexp: RegExp): RegExpMatchArrayIterator
Return Value: Returns a RegExpMatchArrayIterator object, an iterator that yields RegExpMatchArray objects (arrays representing individual matches).
Example 1: To demonstrate getting an email from the given string using the matchAll() method.
Javascript
let text: string =
"Please contact us at support@geeksforgeeks.org or at courses@geeksforgeeks.org" ;
let emailRegex = /\b[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}\b/g;
let emails = text.matchAll(emailRegex);
for (const match of emails) {
console.log( "Found email address:" , match[0]);
}
|
Output:
Found email address: support@geeksforgeeks.org
Found email address: courses@geeksforgeeks.org
Example 2: To demonstrate getting product IDs from given string using matchAll() method.
Javascript
let descriptions: string[] = [
"Product 123 (ABC-DEF) is the best!" ,
"Buy Product ID 456 now!" ,
"This is not a product description." ,
];
const idRegex = /\bProduct\s+(\d+)\b|\bID\s+(\w+)\b/g;
for (const description of descriptions) {
const matches = description.matchAll(idRegex);
for (const match of matches) {
console.log( "Product ID:" , match[1] || match[2]);
}
}
|
Output:
Product ID: 123
Product ID: 456
Share your thoughts in the comments
Please Login to comment...