Check if String contains a specific Character In javascript, we can use String.includes method, The String.includes method returns true if the character is contained in the string. Below we have added multiple examples to determine if the character is contained in the string.
Example 1:
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';
const char = 'o';
console.log(str.includes(char)); // true
if (str.includes(char)) {
// string contains the character
}
Example 2:
If you need to add a case insensitive check, whether a character is contained in a string, just convert the string and character to lowercase.
const str = 'Coding Driver';
const char = 'D';
console.log(str.toLowerCase().includes(char.toLowerCase())); // true
if (str.toLowerCase().includes(char.toLowerCase())) {
//string contains the character
}
Note: The String.includes method is not supported by Internet Explorer 6-11. So, you can use the String.indexOf method instead.
Example 3:
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';
const char = 'd';
console.log(str.indexOf(char));
if (str.indexOf(char)> -1) {
// string contains the character
}
I hope these examples help you to check if string contain a specifix character in javascript;