JavaScript search() Method String.search() Method (Regular Expressions)

This tutorial covers the search() method, part of JavaScript's String object. The search() method is applied on a String, and takes a regular expression pattern as argument. The search() method is identical to indexOf(), except for argument: search() takes a regular expression pattern as argument, while indexOf() takes a String. The search() method returns -1 if not match was found, or the character position index of the first substring match. JavaScript search() method's syntax Both methods belong to JavaScript's String object. But the search() method is covered here because it relies mostly on the power of regular expression pattern matching, and because anyone learning regular expressions will want to know these three String methods: match(), search(), and replace().

Using the search() Method

The search() method behaves like JavaScript's String.indexOf() method: both are applied on a string, and return the position index of the substring matched, of return a (-1) if no match was found.

Unlike indexOf(), the search() method takes a regular expression as argument; the regular expression can be case-insensitive, but cannot be global: it will only return the character position index of the first pattern matched.

alert( "I learn JavaScript.".search(/java/i) );

Because our script was able to match the case-insensitive "java" inside "JavaScript", the search method returned the position index of the matched word's first letter: (remember: first letter is at position index zero) JavaScript search() method

Handling Unsuccessful Matches with the search() Method

Because the search() method returns predictable results in case of failed searches, unsuccessful matches are easy to handle appropriately:

var carter = "VBScript isn't an ideal language for the web.";
if( carter.search(/javascript/i) == -1 )
    alert("Could not find 'JavaScript' inside the string!");

We know that the search() method returns -1 in case of failed match, so we could display an informative message: JavaScript search() method fails to match a regular expression pattern

Test the search() Method

Interactively test the search() method by editing the JavaScript code below and clicking the Test search() Method button.

Browser support for JavaScript search() method
Internet Explorer supports the JavaScript search() methodFirefox supports the JavaScript search() methodSafari supports the JavaScript search() methodOpera supports the JavaScript search() method