Looking to get a head start on your next software interview? Pickup a copy of the best book to prepare: Cracking The Coding Interview!
The match method is used to search a string for a match against a regular expression. It returns an array of matches, or null if no match is found. In TypeScript, you can use the match method on a string variable like this:
const str = "Hello World";
const matches = str.match(/o/g);
console.log(matches); // ["o", "o"]
In this example, we declare a string variable called “str” and assign it the value “Hello World”. We then call the match method on the string and pass in a regular expression that matches the letter “o”. The “g” flag is used to perform a global search, meaning that all matches in the string will be returned.
The match method returns an array of matches, which in this case is [“o”, “o”]. We then log the array to the console.
It’s important to note that the match method returns null if no match is found. You should always check for null before accessing the array of matches.