JavaScript has a method called String.includes()
that checks whether a string contains a substring.
Use of the String.includes() method
The String.includes() method returns true
if the given substring is inside the string, else it will return false
.
const text = "Hello World, how are you?";
const check = text.includes("World");
console.log(check);
// Example with condition
if(check){
console.log("Yes the substring is there.");
}
true
Yes the substring is there.
String.includes() method is Case Sensitive
This method is case-sensitive, which means Hello
is not equal to the hello
.
Now we will see how you can find the substring in a case-insensitive way. To do this we will use the String.toLowerCase()
method that converts all the characters into lowercase.
const text = "Hi John";
const check1 = text.includes("john");
const subText = "joHn";
const lowerMainText = text.toLocaleLowerCase();
const lowerSubText = subText.toLowerCase();
const check2 = lowerMainText.includes(lowerSubText);
/**
* One liner example
* const check2 = text.toLowerCase().includes("JoHn".toLocaleLowerCase());
*/
console.log(check1);
console.log(check2);
false
true