TypeScript String match() method
Last Updated :
28 Feb, 2024
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:
- regexp: Pass RegExp to search for a string.
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.
Javascript
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.
Javascript
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"
Share your thoughts in the comments
Please Login to comment...