JavaScript(JS) string method - search

https‮ww//:‬w.theitroad.com

The search() method is a string method in JavaScript that is used to search for a specified substring in a string and return the index of the first occurrence of the substring, or -1 if the substring is not found.

Here is the syntax for the search() method:

str.search(searchValue)

Here, str is the string you want to search in, and searchValue is the string you want to search for.

The search() method returns the index of the first occurrence of the searchValue in the str, or -1 if the searchValue is not found.

Here is an example of using the search() method:

let str = "hello world";
let index = str.search("world");
console.log(index); // 6

In the example above, the search() method searches for the string "world" in the str and returns the index of the first occurrence of the string, which is 6.

Note that the search() method can also take a regular expression as its argument. In that case, it will search for the first occurrence of the regular expression in the string and return the index of the first match.

Here is an example of using the search() method with a regular expression:

let str = "hello world";
let index = str.search(/o/);
console.log(index); // 4

In the example above, the search() method searches for the regular expression /o/ in the str and returns the index of the first occurrence of the regular expression, which is 4.