JavaScript String Search

String search methods help you find substrings within larger strings. Whether checking if a substring exists or locating its position, these methods are crucial for text processing and validation.

Key Topics

indexOf() and lastIndexOf()

indexOf() returns the first occurrence of a substring, while lastIndexOf() returns the last occurrence.

let text = "Banana";
console.log(text.indexOf("a"));
console.log(text.lastIndexOf("a"));

Output

> 1

> 3

Explanation: In the word "Banana", the first "a" appears at index 1, and the last "a" appears at index 3.

includes(), startsWith(), endsWith()

includes() checks if a substring exists, startsWith() checks if a string begins with a substring, and endsWith() checks if it ends with one.

let phrase = "Hello World";
console.log(phrase.includes("World"));
console.log(phrase.startsWith("Hello"));
console.log(phrase.endsWith("World"));

Output

> true

> true

> true

Explanation: "Hello World" includes "World", starts with "Hello", and ends with "World". All methods return true.

search()

The search() method searches for a substring (or pattern) and returns the index of the first match, or -1 if not found.

let sentence = "The quick brown fox";
console.log(sentence.search("brown"));

Output

> 10

Explanation: The substring "brown" starts at index 10 in the sentence "The quick brown fox".

JavaScript Usage in DOM

This DOM-based example shows how string search methods can validate user input before displaying results.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>String Search in DOM</title>
</head>
<body>
    <h1>String Search Demo</h1>
    <input type="text" id="inputText" placeholder="Type something...">
    <button onclick="checkWord()">Check Word</button>
    <p id="result"></p>

    <script>
        function checkWord() {
            let input = document.getElementById("inputText").value;
            if (input.includes("test")) {
                document.getElementById("result").textContent = "'test' found in input.";
            } else {
                document.getElementById("result").textContent = "'test' not found.";
            }
        }
    </script>
</body>
</html>

Key Takeaways

  • indexOf()/lastIndexOf(): Find positions of substrings.
  • includes(), startsWith(), endsWith(): Check substring existence and placement.
  • search(): Locates substrings or patterns within text.
  • DOM Integration: Validate and respond to user input using search methods.