search()

The search() method is used within regular expressions to search for a match to the given string within the given string. When a match is made, the character place within the string is returned. If no match is found, the method returns -1 as its value. For a full explanation of regular expressions and the RegExp object, see the JavaScript Object Reference, RegExp and regular expression. For the use of the replace() method, see the syntax and example below.

syntax:

stringName.replace(regExpName)

EXAMPLE

var stringToSearch = new String("This the text to be searched.");



var theRegExp = /be /g;



var searchedString = stringToSearch.search(theRegExp);



document.write("The regular expression has found a match in place " + searchedString)

The example starts with the creation of a string called stringToSearch. Next, the regular expression is defined, which is looking for the word "be" and is called theRegExp. The searchedString is then created which performs the search using the search() method on the regular expression theRegExp. Finally, a document.write statement writes some applicable text to the screen, along with the value now contained within searchedString. A match is made in place 17, which is 17 places within the string of text (actually, it is eighteen places within the string of text - JavaScript counts the zero place as "one"). The output should look like the following:



The regular expression has found a match in place 17