Check if String contains a Character #
Use the String.includes[]
method to check if a string contains a character, e.g. if [str.includes[char]] {}
. The include[]
method will return true
if the string contains the provided character, otherwise false
is returned.
Copied!
const str = 'Hello world'; const char = 'e'; console.log[str.includes[char]]; // 👉️ true if [str.includes[char]] { // 👉️ string contains the character }
We used the String.includes method to determine if the character is contained in the string.
This works with special characters as well, e.g. emojis:
Copied!
const str = 'Hello world 🐔'; const char = '🐔'; console.log[str.includes[char]]; // 👉️ true if [str.includes[char]] { // 👉️ string contains the character }
If you need to perform a case insensitive check, for whether a character is contained in a string, convert the string and the character to lowercase when calling String.includes
.
Copied!
const str = 'Hello world'; const char = 'L'; // 👇️ true console.log[str.toLowerCase[].includes[char.toLowerCase[]]]; if [str.toLowerCase[].includes[char.toLowerCase[]]] { // 👉️ string contains the character }
We performed a case-insensitive check by converting the string and the character to lowercase when calling the includes
method.
Alternatively, you can use the String.indexOf
method.
Use the String.indexOf[]
method to check if a string contains a character, e.g. if [str.indexOf[char] !== -1] {}
. The indexOf
method will return the index of the character in the string or -1
if the character is not contained in the string.
Copied!
const str = 'Hello world'; const char = 'l'; // 👇️ 2 console.log[str.indexOf[char]]; if [str.indexOf[char] !== -1] { // 👉️ string contains the character }
We used the indexOf method to check if a string contains a character.
If there is no match, the String.indexOf
method returns -1
.
Our if
statement checks if the indexOf
returned a value other than -1
. If it did, the character is contained in the string.
Which approach you pick is a matter of personal
preference. I'd go with the includes
method as I find it more direct and intuitive.
Further Reading #
- Check if String contains Special Characters in JavaScript
- Remove Special Characters from a String in JavaScript
- Check if String contains only Letters and Numbers in JS
- Check if String contains only Letters and Spaces in JS
- Check if String contains only Latin Letters in JavaScript
- Check if String contains only Digits in JavaScript
- Check if String contains only Spaces in JavaScript
- Check if String contains only Letters in JavaScript
- Check if a String is all Uppercase in JavaScript
- Check if a String ends with a Number in JavaScript
- Check if String starts with Substring in JavaScript
- Check if String contains any Letter in JavaScript