Check if String contains only Latin Letters in JavaScript


Borislav Hadzhiev

Last updated: Oct 21, 2021


Photo from Unsplash

Check if String contains only Latin Letters #

To check if a string contains only latin characters, use the test() method with the following regular expression /^[a-zA-Z]+$/. The test method will return true if the string contains only latin characters andfalse otherwise.

function onlyLatinCharacters(str) { return /^[a-zA-Z]+$/.test(str); } console.log(onlyLatinCharacters('apple')); // 👉️ true console.log(onlyLatinCharacters('Buy groceries')); // 👉️ false console.log(onlyLatinCharacters('pizza,cola')); // 👉️ false
If you also need to match spaces, dots, commas, etc, scroll down to code snippet at the bottom of the article.

We used the RegExp.test method to check if a string contains only latin characters.

The test method returns true if the string is matched in the regex and false otherwise.

The forward slashes / / mark the start and end of the regular expression.

The caret ^ matches the beginning of the input and the dollar sign $ - the end of the input.

The part between the square brackets [] is called a character class and matches a range of lowercase a-z and uppercase A-Z letters.

The plus + matches the preceding item (the letter ranges) 1 or more times.

You can also use the i flag to make the regular expression case insensitive. This would allow you to remove the uppercase range A-Z from the square brackets.
function onlyLatinCharacters(str) { // 👇️ using `i` flag return /^[a-z]+$/i.test(str); } console.log(onlyLatinCharacters('APPLE')); // 👉️ true

The i flag allows us to do case insensitive search and replaces the uppercase range A-Z.

If you ever need help reading a regular expression, check this regex cheatsheet from MDN out.

If you also need to match dots, commas or spaces, etc, add the character you need to match between the square brackets [].

function onlyLatinSpacesDots(str) { return /^[a-zA-Z\s.,]+$/.test(str); } console.log(onlyLatinSpacesDots('apple')); // 👉️ true console.log(onlyLatinSpacesDots('Buy groceries')); // 👉️ true console.log(onlyLatinSpacesDots('pizza.cola')); // 👉️ true

In this example we match latin characters, whitespace characters (\s), dots and commas.

The \s special character matches spaces, tabs and new lines.

You can update this as you need, by adjusting the characters between the square brackets [].

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.