TypeScript String search() Method
The search() method is an inbuilt function in TypeScript that is used to search for a match between a regular expression and a string. It returns the index of the first match, or -1 if no match is found.
Syntax
string.search(regexp);
Parameter
This methods accept a single parameter as mentioned above and described below:
- regexp: This parameter is a RegExp object.
Return Value:
- The method returns the index of the regular expression inside the string. If no match is found, it returns -1.
Examples of TypeScript String search() Method
Example 1: Finding a Substring with search()
In this example, we use the search() method to find the position of a substring that matches a regular expression.
let str: string = "Hello, welcome to TypeScript!";
let index: number = str.search(/welcome/);
if (index !== -1) {
console.log("Found at index:", index);
} else {
console.log("Not Found");
}
Output:
Found at index: 7
Example 2: No Match Found with search()
In this example, we use the search() method to look for a substring that does not exist in the string.
let str: string = "Hello, welcome to TypeScript!";
let index: number = str.search(/world/);
if (index !== -1) {
console.log("Found at index:", index);
} else {
console.log("Not Found");
}
Output:
Not Found