JavaScript » String » search

Syntax:
object.search(regexp)

This method is used to search for a match between a regular expression and the specified string.

This method is used to search for a match between a regular expression and the specified string. If a match is found, the search method returns the index of the regular expression within the string. If no match is found, a value of -1 is returned.

Examples

Code:
myString = new String("Go to DevGuru.com")
rExp = /devguru.com/gi;
results = myString.search(rExp)
document.write(results)
Output:
6
Explanation:

This example of code below uses the search method to look for a match between the regular expression 'rExp' and the characters in the 'myString' string object and displays the resulting value in the browser.

Code:
myString = new String("Go to DevGuru.com")
rExp = /devguru.com/g;
results = myString.search(rExp)
document.write(results)
Output:
-1
Explanation:

In this example, removing the 'i' (ignore case) flag from the regular expression causes the value of the search to be returned as -1.