TypeScript String matchAll() Method
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@w3wiki.net or at courses@w3wiki.net" ; 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@w3wiki.net
Found email address: courses@w3wiki.net
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
Contact Us