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

                 

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

There are several ways to check if a string contains a substring in JavaScript.
The simplest and most common way is to use the indexOf() method of the String object. This method returns the index within the string of the first occurrence of the specified substring, or -1 if the substring is not found. For example:
let str = "Hello World";
let subStr = "World";
let result = str.indexOf(subStr);
// result will be 6, which is the index of the substring "World" in the string "Hello World"
If you want a more robust solution, you can use the includes() method of the String object. This method returns a boolean value indicating whether or not the specified substring is found in the string. For example:
let str = "Hello World";
let subStr = "World";
let result = str.includes(subStr);
// result will be true, since the string "Hello World" contains the substring "World"

Post a Comment

0 Comments