TypeScript string search method:
String search() method of TypeScript is used to search for a substring in a string by using a regular expression or regex.
In this post, we will learn how to use search() with example in TypeScript.
Definition of search:
search() method is defined as below:
str.search(regex);
Here, regex is the regular expression that we are using for the search. It returns one number. If the match is found, it returns the first index of the match found and if it is not found, it returns -1.
Example of search():
Let’s try it with an example.
let given_str = "Hello World Hello World 0123";
console.log(given_str.search("World"));
console.log(given_str.search("Worldx"));
console.log(given_str.search(/[0-9]/g));
If you run this program, it will print the below output:
6 - 1;
24;
Here,
- For the first one, it searches for World in the string, and returns the index of the first World word.
- For the second one, it searches for Worldx. Since it is not in the string, it returns -1.
- For the last one, it uses a regular expression to find the first number in the string and returns the index of 0.
Use search() to check if a word is in a string or not:
We can also use the search() method to check if a word exists in a string or not. We need to check the return value is -1 or not for that. For example:
let given_str = "Hello World Hello World 0123";
let word = "World";
if (given_str.search(word) == -1) {
console.log("Not found !!");
} else {
console.log("Found !!");
}
It will check if the word is in given_str or not. Based on the return value of search(), it prints one message.