JavaScript: Check if a String Contains Another String

Introduction

In many programming tasks, you might need to check if one string contains another substring. JavaScript provides an easy way to do this using the includes() method, which checks if a string contains a specified substring and returns true or false. This is a common operation in text processing and validation.

Problem Statement

Create a JavaScript program that:

  • Accepts two strings: one main string and one substring.
  • Checks if the main string contains the specified substring.
  • Returns and displays the result (true or false).

Example:

  • Input: Main String: "Hello world", Substring: "world"

  • Output: true

  • Input: Main String: "JavaScript is fun", Substring: "Python"

  • Output: false

Solution Steps

  1. Read the Input Strings: Provide the main string and the substring either as user input or directly in the code.
  2. Check for Substring: Use the includes() method to check if the main string contains the substring.
  3. Display the Result: Print true if the substring is found, otherwise print false.

JavaScript Program

// JavaScript Program to Check if a String Contains Another String
// Author: https://www.javaguides.net/

function containsSubstring(mainString, substring) {
    // Step 1: Use the includes() method to check for the substring
    return mainString.includes(substring);
}

// Example input
let mainString = "Hello world";
let substring = "world";
let result = containsSubstring(mainString, substring);
console.log(`Does the string "${mainString}" contain "${substring}"? ${result}`);

Output

Does the string "Hello world" contain "world"? true

Example with Different Input

let mainString = "JavaScript is fun";
let substring = "Python";
let result = containsSubstring(mainString, substring);
console.log(`Does the string "${mainString}" contain "${substring}"? ${result}`);

Output:

Does the string "JavaScript is fun" contain "Python"? false

Explanation

Step 1: Use the includes() Method

  • The includes() method checks if the main string contains the specified substring. It returns true if the substring is found and false otherwise. The method is case-sensitive, meaning "Hello" and "hello" would not be considered the same.

Step 2: Return and Display the Result

  • The result is returned by the function and printed using console.log().

Conclusion

This JavaScript program demonstrates how to check if one string contains another substring using the includes() method. This method is simple and efficient for performing substring searches, and it can be applied to various text processing tasks such as input validation, searching, or filtering data.

Comments