Check if String contains specific Character in JavaScript

avatar

Borislav Hadzhiev

Mon Oct 04 20212 min read

Check if String contains a Character #

To check if a string contains a specific character in Javascript, call the String.includes method, e.g. string.includes(myChar). The String.includes method returns true if the character is contained in the string.

index.js
// Not Supported in IE 6-11 const str = 'Hello world'; const char = 'e'; console.log(str.includes(char)); // ๐Ÿ‘‰๏ธ true if (str.includes(char)) { // ๐Ÿ‘‰๏ธ string contains the character }

In the code snippet, 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, whether a character is contained in a string, convert the string and 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 }

In the code snippet we have converted both - the string we called the includes method on and the character to lowercase to perform a case insensitive search.

The String.includes method is not supported by Internet Explorer 6-11, if you have to support IE, you can use the String.indexOf method instead.

To check if a string contains a specific character in Javascript, call the String.indexOf method, e.g. string.indexOf(myChar). The String.indexOf method will return the index of the match or -1 if there is no match.

index.js
// Supported in IE 6-11 const str = 'Hello world'; const char = 'l'; // ๐Ÿ‘‡๏ธ 2 console.log(str.indexOf(char)); if (str.indexOf(char) !== -1) { // ๐Ÿ‘‰๏ธ string contains the character }

In the code snippet we call the indexOf method on the string and pass the character as the only parameter.

The the example the String.indexOf method returns 2, because the character l matches the same character in the string at index 2.

If there is no match the method returns -1.

Our conditional statement checks if the indexOf returned a value other than -1, if it did, the character is contained in the string.

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee