Open In App

TypeScript String match() method

TypeScript has a built-in match() function which is used to find a match, within a string against any given regular expression. If the match is discovered it will return it as an array.

Syntax:

string.match(regexp: string | RegExp): RegExpMatchArray | null

Parameters:

Return Value

If the match is found, then it returns an array that contains the matches otherwise returns Null.



Example 1: To demonstrate matching a simple pattern “world” using match() method.




let text: string = "Hello, world!";
let matches: RegExpMatchArray | null = text
    .match(/world/);
console.log(matches);

Output:



["world"] 

Example 2: To demonstrate capturing a group using string match() method.




let sentence: string = "The price is $12.99.";
let priceMatch: RegExpMatchArray | null = sentence
    .match(/\$(\d+)\.(\d+)/);
 
if (priceMatch) {
    console.log("Dollars:", priceMatch[1]);
    console.log("Cents:", priceMatch[2]);
}

Output:

"Dollars: 12"
"Cents: 99"
Article Tags :