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 Objectlet stringWithMatch = "I am a doctor.";let stringWithoutMatch = "I am coder";let regExp = new RegExp("(doctor|painter)");stringWithMatch.search(regExp); // 7stringWithoutMatch.search(regExp); // -1console.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…
-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"); // 7console.log("found index is " + foundAtIndex);