How to check whether a string contains a substring in JavaScript?

Introduction

Checking whether a string contains a substring is a common task in JavaScript. In this guide, we'll explore various methods to achieve this, providing you with the knowledge to handle string manipulation effectively.

Syntax

Before diving into examples, let's understand the basic syntax for checking whether a string contains a substring:

Both methods return a boolean indicating whether the substring is present in the given string.

Best Answer

When choosing between `indexOf()` and `includes()`, the best answer depends on your specific use case. Use `indexOf()` if you need the position of the substring, and `includes()` if you only need a boolean result.

Examples

Let's explore examples to illustrate the usage of these methods:


        // Example 1: Using indexOf()
        var str1 = "Hello, World!";
        var substring1 = "World";

        if (str1.indexOf(substring1) !== -1) {
            console.log("Substring found!");
        } else {
            console.log("Substring not found.");
        }

        // Example 2: Using includes()
        var str2 = "JavaScript is amazing!";
        var substring2 = "amazing";

        if (str2.includes(substring2)) {
            console.log("Substring found!");
        } else {
            console.log("Substring not found.");
        }
    

Explanation

Let's delve deeper into the reasons behind the observed behavior of each method:

Method 1: `indexOf()`

The `indexOf()` method returns the position of the first occurrence of a specified value in a string. If the value is not found, it returns -1.

Method 2: `includes()`

The `includes()` method determines whether one string may be found within another string and returns a boolean value.

Case Studies

Let's examine specific cases where choosing one method over the other makes sense:

Case Study 1: Searching for Multiple Substrings

When searching for multiple substrings, using `includes()` might be more concise:


        var str = "The quick brown fox jumps over the lazy dog";
        var substrings = ["fox", "cat", "dog"];

        for (var i = 0; i < substrings.length; i++) {
            if (str.includes(substrings[i])) {
                console.log(substrings[i] + " found!");
            } else {
                console.log(substrings[i] + " not found.");
            }
        }
    

Case Study 2: Case-Insensitive Search

If you need a case-insensitive search, convert both the string and the substring to lowercase (or uppercase) before using `indexOf()` or `includes()`:


        var str = "The Quick Brown Fox";
        var substring = "quick";

        if (str.toLowerCase().includes(substring.toLowerCase())) {
            console.log("Substring found!");
        } else {
            console.log("Substring not found.");
        }
    

Examples with Answers

Let's test your understanding with some examples:

Example 1:

What will be the output of the following code?


        var str = "Hello, World!";
        var substring = "world";

        if (str.indexOf(substring) !== -1) {
            console.log("Substring found!");
        } else {
            console.log("Substring not found.");
        }
    

Answer: The output will be "Substring not found." since `indexOf()` is case-sensitive, and "world" is not the same as "World".

Example 2:

How can you modify the code to make it case-insensitive?


        // Modified code for case-insensitive search
        var str = "Hello, World!";
        var substring = "world";

        if (str.toLowerCase().indexOf(substring.toLowerCase()) !== -1) {
            console.log("Substring found!");
        } else {
            console.log("Substring not found.");
        }
    

Exams with Answers

Let's challenge your knowledge with a couple of exams:

Exam 1:

Write a function named `containsSubstring` that takes two parameters, `str` and `substring`, and returns true if `str` contains `substring`, and false otherwise.


        // Function to check if a string contains a substring
        function containsSubstring(str, substring) {
            // Your code here
        }
    

Answer:


        function containsSubstring(str, substring) {
            return str.includes(substring);
        }
    

Exam 2:

Explain the difference between using `indexOf()` and `includes()` when checking for a substring.

Answer: The main difference lies in the return values. `indexOf()` returns the position of the first occurrence of the substring in the string or -1 if not found. On the other hand, `includes()` returns a boolean indicating whether the substring is present in the string or not.

Exercises with Answers

Test your understanding with these hands-on exercises:

Exercise 1:

Write a function named `startsWithVowel` that takes a string as a parameter and returns true if the string starts with a vowel (a, e, i, o, u), and false otherwise.


        // Function to check if a string starts with a vowel
        function startsWithVowel(str) {
            // Your code here
        }
    

Answer:


        function startsWithVowel(str) {
            var firstChar = str.toLowerCase().charAt(0);
            return ['a', 'e', 'i', 'o', 'u'].includes(firstChar);
        }
    

Exercise 2:

Write a function named `countOccurrences` that takes two parameters - a string and a substring - and returns the number of times the substring appears in the string.


        // Function to count occurrences of a substring in a string
        function countOccurrences(str, substring) {
            // Your code here
        }
    

Answer:


        function countOccurrences(str, substring) {
            var count = 0;
            var index = str.indexOf(substring);
            while (index !== -1) {
                count++;
                index = str.indexOf(substring, index + 1);
            }
            return count;
        }
    

Feel free to test your solutions with different inputs.

Questions and Answers

Explore common questions about checking for substrings in JavaScript:

Question 1:

What is the difference between `indexOf()` and `includes()` when checking for a substring?

Answer: The main difference is in the return values. `indexOf()` returns the position of the first occurrence of the substring in the string or -1 if not found. `includes()` returns a boolean indicating whether the substring is present in the string or not.

Question 2:

Can you perform a case-sensitive check for substrings using `includes()`?

Answer: No, `includes()` performs a case-sensitive check. To perform a case-insensitive check, convert both the string and the substring to lowercase (or uppercase) before using `includes()`.

Best Practices with Examples

Follow these best practices to enhance your substring checking code:

Best Practice 1: Use `includes()` for simple existence checks:


        var str = "Hello, World!";
        var substring = "World";

        if (str.includes(substring)) {
            console.log("Substring found!");
        } else {
            console.log("Substring not found.");
        }
    

Best Practice 2: Utilize `indexOf()` for position-based information:


        var str = "JavaScript is amazing!";
        var substring = "amazing";

        var position = str.indexOf(substring);

        if (position !== -1) {
            console.log("Substring found at position: " + position);
        } else {
            console.log("Substring not found.");
        }
    

Best Practice 3: Be mindful of case sensitivity:


        var str = "Hello, World!";
        var substring = "world";

        if (str.toLowerCase().includes(substring.toLowerCase())) {
            console.log("Substring found!");
        } else {
            console.log("Substring not found.");
        }
    

Adhering to these practices ensures robust and reliable substring checking in your JavaScript code.

Alternatives

Consider alternative approaches when working with substring checks:

Alternative 1: Regular Expressions:

Regular expressions provide powerful and flexible pattern matching. Use the `test` method to check for substring existence:


        var str = "Hello, World!";
        var substring = "World";
        var regex = new RegExp(substring);

        if (regex.test(str)) {
            console.log("Substring found!");
        } else {
            console.log("Substring not found.");
        }
    

Alternative 2: `startsWith()` and `endsWith()`:

For checking whether a string starts or ends with a specific substring:


        var str = "Hello, World!";
        var startsWith = "Hello";
        var endsWith = "World";

        console.log(str.startsWith(startsWith)); // true
        console.log(str.endsWith(endsWith)); // true
    

Explore these alternatives based on your specific requirements and coding style.

Multiple-Choice Questions (MCQ)

Test your understanding of substring checking in JavaScript with these multiple-choice questions:

Question 1:

What does the `indexOf()` method return when the substring is not found in the string?

Correct Answer: a

Question 2:

Which method is suitable for case-sensitive substring checking?

Correct Answer: b

Review your answers to assess your comprehension of substring-related concepts.

All Scenarios and Use Cases

Explore various scenarios and use cases where checking for substrings is crucial:

Scenario 1: Highlighting Search Results:

Use substring checks to highlight search results in a text document or web page:


        var searchText = "JavaScript";
        var content = "JavaScript is a powerful scripting language.";

        if (content.toLowerCase().includes(searchText.toLowerCase())) {
            // Highlight the search result
            console.log(content.replace(new RegExp(searchText, 'gi'), '$&'));
        }
    

Scenario 2: Form Validation:

Ensure that user input contains specific substrings during form validation:


        var userInput = document.getElementById('username').value;

        if (userInput.includes('admin')) {
            alert('Username cannot contain the word "admin".');
        }
    

Explore these scenarios to make informed decisions based on your coding requirements.

Quizzes

Deepen your knowledge by taking these quizzes related to substring checking in JavaScript:

Quiz 1:

What is the output of the following code?


        var str = "Hello, World!";
        var substring = "world";

        console.log(str.toLowerCase().includes(substring.toLowerCase()));
    

a) true

b) false

c) undefined

d) Error

Correct Answer: a

Quiz 2:

When might you prefer using `indexOf()` over `includes()`?

a) Always

b) When checking for the position of the substring

c) When performing a case-insensitive check

d) Never

Correct Answer: b

Check your understanding with these quizzes and enhance your proficiency in substring checking.

Advanced Examples

Dive into advanced examples showcasing intricate scenarios involving substring checking in JavaScript:

Example 1: Extracting URL Parameters:

Use substring checks to extract specific parameters from a URL:


        var url = "https://example.com?param1=value1¶m2=value2";
        var paramName = "param1";

        var startIndex = url.indexOf(paramName);
        var endIndex = url.indexOf("&", startIndex);

        var paramValue = url.substring(startIndex + paramName.length + 1, endIndex !== -1 ? endIndex : undefined);

        console.log(paramValue);
    

Example 2: Dynamic CSS Class Addition:

Add a CSS class to an element dynamically based on substring checks:


        var element = document.getElementById('myElement');
        var forbiddenClass = "forbidden";

        if (element.textContent.includes(forbiddenClass)) {
            element.classList.add('highlight');
        }
    

Explore these advanced examples to gain a deeper understanding of substring checking nuances in JavaScript.

Notes

Consider the following essential notes when working with substring checks in JavaScript:

Be aware of these notes to make informed decisions based on your specific coding scenarios.

Tutorial: Step-by-Step with Source Code Example for Each Step

Follow this step-by-step tutorial to master substring checks in JavaScript with detailed source code examples for each step:

Step 1: Introduction to Substring Checks


        // Step 1 code example
        console.log('Learn the basics of substring checks in JavaScript.');
    

Step 2: Using `includes()` for Simple Checks


        // Step 2 code example
        var str = "Hello, World!";
        var substring = "World";

        console.log(str.includes(substring)); // true
    

Step 3: Employing `indexOf()` for Positional Information


        // Step 3 code example
        var str = "JavaScript is amazing!";
        var searchTerm = "is";

        console.log(str.indexOf(searchTerm)); // 11
    

Walk through each step with corresponding code examples to grasp the concepts effectively.

Most Asked Questions with Answers

Address common queries related to substring checks in JavaScript:

Question 1: Can `includes()` be used for case-insensitive substring checks?

Answer: No, `includes()` is case-sensitive. Use methods like `toLowerCase()` to perform case-insensitive checks.

Question 2: What is the difference between `indexOf()` and `search()` for substring checks?

Answer: While both methods search for substrings, `search()` allows the use of regular expressions, providing more advanced search capabilities.

Clarify your doubts by exploring these frequently asked questions and their concise answers.

Summaries

Recap the key points related to substring checks in JavaScript:

Syntax

Best Answer

All Scenarios and Use Cases

Examples with Answers

  1. Checking for a specific word:
    JavaScript
    const text = "Welcome to the JavaScript world!";
    const containsJavaScript = text.includes("JavaScript"); // true
    
  2. Finding the position of a character:
    JavaScript
    const firstCommaIndex = text.indexOf(","); // 11
    
  3. Counting occurrences of a substring:
    JavaScript
    const string = "hello hello hello";
    let count = 0;
    let index = string.indexOf("hello");
    while (index !== -1) {
        count++;
        index = string.indexOf("hello", index + 1);
    }
    console.log(count); // 3
    

Exercises with Answers

  1. Write a function that checks if a string starts with a vowel.
    JavaScript
    function startsWithVowel(str) {
        const vowels = "aeiouAEIOU";
        return vowels.includes(str[0]);
    }
    
  2. Write a function that reverses a string.
    JavaScript
    function reverseString(str) {
        return str.split("").reverse().join("");
    }
    

Questions and Answers

Best Practices and Examples