The search() method searches the string for the specified value and returns its position of the match. The search value can be the string or regular expression. The search method returns -1 if no match is found.
The searchValue parameter is required, and it is a regular expression. The string will automatically be converted to the regular expression. The method returns a Number, representing the position of the first occurrence of the specified searchValue, or -1 if no match is found.
// app.js let str = 'Obama was US president'; let result = str.search('was'); console.log(result);
So, in the above example, it searches for was substring and if found then it will return the index of that string. In our case, its position is 6, so it returns the 6.
The argument of the search() method is a regular expression object. If the non-RegExp object is passed, it is implicitly converted to a RegExp by using a new RegExp().
When you want to know whether the pattern is found and also its index in the string then use the search() method.
// app.js let str = 'Jude Law'; let result1 = /[A-Z]/g; var result2 = /[.]/g; console.log(str.search(result1)); console.log(str.search(result2));