Check if String contains specific Character in JavaScript

avatar

Borislav Hadzhiev

Last updated: Jul 25, 2022

banner

Photo from Unsplash

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.

index.js
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:

index.js
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.

index.js
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.

index.js
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 #

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.