JavaScript: Check if a String Contains Another String

1. Introduction

A common task in programming is to determine whether a given string (often called the "main string") contains another string (often called the "substring"). JavaScript offers several methods to perform this check, and in this guide, we'll use the includes() method of the string prototype to achieve this.

2. Program Overview

For this guide, we will:

1. Define a main string and a substring.

2. Use the includes() method to check if the main string contains the substring.

3. Display the result.

3. Code Program

let mainString = "JavaScript is an amazing programming language!";
let substring = "amazing";

// Using the includes() method to check if mainString contains substring
let containsSubstring = mainString.includes(substring);

console.log(The main string "${mainString}" ${containsSubstring ? 'contains' : 'does not contain'} the substring "${substring}".);

Output:

The main string "JavaScript is an amazing programming language!" contains the substring "amazing".

4. Step By Step Explanation

1. String Initialization: We start with a main string mainString and a substring which we want to check for.

2. Using the includes() Method:

- The includes() method determines whether one string may be found within another string. It returns true if the substring is found, and false otherwise.

- We pass our substring as an argument to the includes() method of our mainString to perform the check.

3. Displaying the Result: After checking, we use a template string to display the result. If containsSubstring is true, our output indicates the presence of the substring; otherwise, it indicates its absence.

Comments