Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

javascript
communitycreator

What is the search method in JavaScript String?

Programming Bytes

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

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);

RELATED TAGS

javascript
communitycreator

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring