The search() method executes a search for a match between a regular expression and this String object.



A regular expression object. If a non-RegExp object obj is passed, it is implicitly converted to a RegExp by using new RegExp(obj).


If successful, search() returns the index of the first match of the regular expression inside the string. Otherwise, it returns -1.

When you want to know whether a pattern is found in a string use search() (similar to the regular expression test() method); for more information (but slower execution) use match() (similar to the regular expression exec() method).


Using search()

The following example logs a message which depends on the success of the test.

function testinput(re, str) {
  var midstring;
  if ( != -1) {
    midstring = ' contains ';
  } else {
    midstring = ' does not contain ';
  console.log(str + midstring + re);

Gecko-specific notes

  Created by Mozilla Contributors, license: CC-BY-SA 2.5