What is the search method in JavaScript String?

What is the search method?

In JavaScript, we can use the search method to check if the string matches a regular expression.

let string = "I am a doctor.";
let foundAtIndex = string.search(/(doctor|painter)/);
console.log(`pattern ~${/(doctor|painter)/}~ found at index ${foundAtIndex}`);
// using regex Object
let stringWithMatch = "I am a doctor.";
let stringWithoutMatch = "I am coder";
let regExp = new RegExp("(doctor|painter)");
stringWithMatch.search(regExp); // 7
stringWithoutMatch.search(regExp); // -1
console.log(`pattern ~${regExp.toString()}~ found at index ${stringWithMatch.search(regExp)}`);
console.log(`pattern ~${regExp.toString()}~ found at index ${stringWithoutMatch.search(regExp)}`);

The search method will check if the pattern passed matches the string…

  • If the pattern matches, then the first index where the pattern is found on the string will be returned.
  • If the pattern is not matched, it will return -1.

We can also send a string as an argument to the search method, and it will internally convert the string as a regex:

let stringWithMatch = "I am a doctor.";
let foundAtIndex = stringWithMatch.search("doctor"); // 7
console.log("found index is " + foundAtIndex);

Free Resources