In this blog post, we will dive into the search() method of JavaScript strings. This method allows you to find the position of the first occurrence of a specific string within another string.
The search() method returns the index of the start of the occurrence, or -1 if the string is not found. Let’s have a look at some examples:
'JavaScript'.search('Script') // returns 4
'JavaScript'.search('TypeScript') // returns -1
As you can see, in the first example, the search string ‘Script’ is found starting at index 4 within the string ‘JavaScript’. However, in the second example, the search string ‘TypeScript’ is not found, so the method returns -1.
The interesting thing is that you can also perform searches using regular expressions. In fact, even if you pass a regular string as the search parameter, it is internally treated as a regular expression. Let’s see some more examples:
'JavaScript'.search(/Script/) // returns 4
'JavaScript'.search(/script/i) // returns 4
'JavaScript'.search(/a+v/) // returns 1
In the above examples, we use regular expressions as the search parameter. The /Script/
regular expression finds the string ‘Script’ at index 4 within ‘JavaScript’, and the /script/i
regular expression performs a case-insensitive search, still finding the string at index 4.
Finally, the /a+v/
regular expression searches for one or more occurrences of the letter ‘a’, finding the first occurrence starting at index 1 within ‘JavaScript’.
In conclusion, the search() method is a powerful tool for finding the position of a specific string within another string in JavaScript. It allows for both string and regular expression searches, giving you flexibility and control.
Tags: JavaScript, search, string method, regular expression