Skip to main content

JavaScript Strings

JavaScript String Search

Written by Published

includes, indexOf, startsWith and endsWith find text inside a string.

includes answers yes or no.

indexOf tells you where, or gives -1 when there is no match.

Example

Example

javascript

const text = "JavaScript Basics";

console.log(text.includes("Script"));
console.log(text.indexOf("Basics"));

The output is true then 11.

The Search Methods

includes returns true or false.

indexOf returns the first position, or -1.

startsWith and endsWith check the ends.

Syntax

Syntax

javascript

text.includes("part");
text.indexOf("part");

All of them are case sensitive.

Checking the Ends

These read far better than comparing slices by hand.

Example

Example

javascript

const file = "report.pdf";

console.log(file.endsWith(".pdf"));
console.log(file.startsWith("report"));

Both are true.

No Match

indexOf gives -1, which is why the old check compared against it.

Example

Example

javascript

const text = "hello";

console.log(text.indexOf("z"));
console.log(text.includes("z"));

includes says the same thing more clearly.

Finding the Last Match

lastIndexOf searches from the end.

Example

Example

javascript

const path = "a/b/c";

console.log(path.indexOf("/"));
console.log(path.lastIndexOf("/"));

The output is 1 then 3.

Case Sensitivity

Lowercase both sides when case should not matter.

Example

Example

javascript

const title = "JavaScript";

console.log(title.includes("script"));
console.log(title.toLowerCase().includes("script"));

The output is false then true.

Searching from a Position

The second argument says where to start.

Example

Example

javascript

const text = "abcabc";

console.log(text.indexOf("a"));
console.log(text.indexOf("a", 1));

The output is 0 then 3.

Complete Example

Complete Example

html

<!DOCTYPE html>
<html>
<head>
  <title>JavaScript String Search</title>
</head>
<body>

  <h1>String Search</h1>

  <input id="term" value="script">

  <p id="out"></p>

  <script>
    const text = "JavaScript Basics";
    const term = document.getElementById("term").value;

    document.getElementById("out").innerHTML =
      "Searching for: " + term +
      "<br>Found: " + text.toLowerCase().includes(term.toLowerCase()) +
      "<br>Position: " + text.toLowerCase().indexOf(term.toLowerCase());
  </script>

</body>
</html>

Try It Yourself

Run the above example in the Try It Editor.

Try a missing word:

Search for something not there and see the -1.

Important Points

  • includes returns true or false.
  • indexOf returns a position or -1.
  • lastIndexOf searches from the end.
  • startsWith and endsWith check the ends.
  • All of them are case sensitive.

Conclusion

includes covers most everyday searching.

Reach for indexOf only when you need the position.

Remember to handle case when the text comes from a person.