Check if string contains specific character
Given a string and character, check if the string contains specified character using JavaScript.
Solution
To check if a string contains a given character using JavaScript, we can use String.includes() method. call includes()
method on the string, and pass the specific character (as a string) as argument. includes()
returns true
if the string contains the specified character, or false
if the string does not contain the character.
Program
1. given string is str
and character is ch
. check if string str
contains ch
str = "hello world";
ch = "w";
if ( str.includes(ch) ) {
console.log('string contains specified character');
} else {
console.log('string does not contain specified character');
}