๐ŸŽ“ A1Learner
๐Ÿ”

JavaScript String Search

String search methods are tools that look for text inside a string. They report a position, or a simple true or false answer.

Finding a position

indexOf looks for text inside a string and reports where the first match starts. A search with no match reports -1.

let sentence = "the cat sat";
console.log(sentence.indexOf("cat"));
console.log(sentence.indexOf("dog"));

Yes or no answers

includes answers true when the text is present and false when it is not.

let email = "ana@example.com";
console.log(email.includes("@"));
console.log(email.includes("zzz"));

Checking the start

startsWith checks the opening characters of a string.

let fileName = "report.pdf";
console.log(fileName.startsWith("report"));
console.log(fileName.startsWith("data"));

Example

let address = "ana@example.com";
console.log(address.indexOf("@"));
console.log(address.includes("example"));
console.log(address.startsWith("ana"));
console.log(address.indexOf("org"));

Key points

  • lastIndexOf reports the position of the last match instead of the first.
  • The endsWith method checks the closing characters of a string.
  • The search method reports the position of a match for a pattern.
  • A match at the very start of a string sits at position 0.

In this example, indexOf finds the @ sign at position 3 in the address. includes confirms that the text "example" sits inside the address, and startsWith confirms the opening text "ana". The last indexOf call looks for "org", finds no match, and reports -1.

Try it Yourself

Edit the code, then press Run.

Runs in your browser โ€” the preview under the editor is the real result. Nothing is sent to a server. The code runner panel (right) does the same with more room.

Exercise

What does indexOf return when the text is not found?