How to Check if a String Contains a Character in JavaScript

Last updated on June 16, 2022
How to Check if a String Contains a Character in JavaScript

In this article, we'll be looking at different ways to quickly check if a string contains a specific character in JavaScript.

1. String includes() Method

To check if a string contains a particular character, we can call the includes() method on the string, passing the character as an argument e.g., str.includes(char). The includes() method returns true if the string contains the character, and false if it doesn't.

const str = 'Bread and Milk';

const char1 = 'd';
const char2 = 'p';

console.log(str.includes(char1)); // true

console.log(str.includes(char2)); // false

2. String indexOf() Method

We can also use the indexOf() method to check if a string contains a particular character. We call the indexOf() method on the string, passing the character as an argument. Then we compare the result with -1. For example:

const str = 'Bread and Milk';

const char1 = 'd';
const char2 = 'p';

console.log(str.indexOf(char1) > -1); // true

console.log(str.indexOf(char2) > -1); // false

The indexOf() method searches a string for a value and returns the index of the first occurrence of that value. If the value can't be found, it returns -1.

const str = 'Bread and Milk';

const char1 = 'd';
const char2 = 'p';

console.log(str.indexOf(char1)); // 4

console.log(str.indexOf(char2)); // -1

This is why we compare the result of indexOf() with -1 to check if the character is in the string.

3. Regex Matching

We can test the string against regex patterns to determine if it contains a particular character. One way to do this is with the RegExp test() method.

const str = 'Bread and Milk';

console.log(/d/.test(str)); // true

console.log(/p/.test(str)); // false

The test() method searches the string for a match with the regex. It returns true if it finds a match, and false otherwise.

Using regex matching allows us to specify multiple characters to search for in the string easily.

const str = 'Bread and Milk';

// Contains a digit?
console.log(/\d/.test(str)); // false

// Contains 'r', 'l' or 'c'?
console.log(/[rlc]/.test(str)); // true

// Contains whitespace?
console.log(/\s/.test(str)); // true
Coding Beauty Assistant logo

Try Coding Beauty AI Assistant for VS Code

Meet the new intelligent assistant: tailored to optimize your work efficiency with lightning-fast code completions, intuitive AI chat + web search, reliable human expert help, and more.

See also