javascript Check if a String contains a Substring

javascript Check if a String contains a Substring Example; In this tutorial you will learn how to check if string has a substring in javascript;

Check if String contains a specific substring In javascript, we can use String.includes method, The String.includes method returns true if the character is contained in the string. 

Check if a String contains a Substring with String.includes

The includes() method returns true if a string contains a specified string. Otherwise it returns false. The includes() method is case sensitive.

const str = 'coding driver site';
const char = 'driver';

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

if (str.includes(char)) {
  // string contains the character
}

The String.includes method is case sensitive. To do a case insensitive check if a substring is contained in a string, convert both strings to lowercase.

const str = 'Coding DRIVER';
const char = 'driver';

console.log(str.toLowerCase().includes(char.toLowerCase())); // true

if (str.toLowerCase().includes(char.toLowerCase())) {
  //string contains the character
}

Check if a String contains a Substring with String.indexOf

Check if a string contains a specific character in Javascript, You can use String.indexOf method as well. The String.indexOf method will return the index of the match or -1 if there is no match.

const str = 'coding driver website';
const char = 'driver';

console.log(str.indexOf(char));

if (str.indexOf(char)> -1) {
  // string contains the character
}

The String.indexOf method returns the starting index of the substring or -1 if the substring is not contained in the string.

I hope these examples help you to check if string contain a specified string in javascript;