How to check if JavaScript string contains a character

To find a character in a String has to use a includes() method in JavaScript program. Another way to a string contains a certain character using a regular expression.

They include() method finds the “contains” character in whole string, it will return a true.

Example 1: Find a “t” character in the string.

Output: true

Example 2: Find a “z” char in string.

Output: false

Note: The includes() method is case sensitive, so Uppercase and Lowercase characters different.

Q: How to Javascript check if the string contains only a certain character?

Answer: Return true if a given string has only a certain character and any number of occurrences of that character.

The below example will pop-up an alert box with the result.

Output:

Javascript check if the string contains only a certain character

Q: How to check if a string contains [a-zA-Z] characters only?

Answer: No jQuery Needed, You can use a regex:

The i makes the regex case-insensitive. You could also do.

Do comment if you knew any other ways or have any doubts about this tutorial.

Note: The Examples are tested on Safari browser (Version 12.0.2) and Chrome.
OS: macOS 10.14 Mojave
Code: HTML 5 Version


One thought on “How to check if JavaScript string contains a character

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.