Categories
JavaScript Answers

How to check if a string has any non-ASCII characters in it with JavaScript?

Spread the love

Sometimes, we want to check if a string has any non-ASCII characters in it with JavaScript.

In this article, we’ll look at how to check if a string has any non-ASCII characters in it with JavaScript.

How to check if a string has any non-ASCII characters in it with JavaScript?

To check if a string has any non-ASCII characters in it with JavaScript, we can check with a regex.

For instance, we write:

const str = 'abc'
const hasMoreThanAscii = !/^[\u0000-\u007f]*$/.test(str)
console.log(hasMoreThanAscii)

const str2 = '😀'
const hasMoreThanAscii2 = !/^[\u0000-\u007f]*$/.test(str2)
console.log(hasMoreThanAscii2)

to use the /^[\u0000-\u007f]*$/ regex to check if any characters in str and `str2 have only ASCII characters.

ASCII characters have codes ranging from u+0000 to u+007f.

We call test to check if str and str2 matches the regex pattern.

Then we negate the result to check if the string has any non-ASCII characters.

Therefore, hasMoreThanAscii is false and hasMoreThanAscii2 is true.

Conclusion

To check if a string has any non-ASCII characters in it with JavaScript, we can check with a regex.

2 replies on “How to check if a string has any non-ASCII characters in it with JavaScript?”

Leave a Reply

Your email address will not be published.

If you like the content of this blog, subscribe to my email list to get exclusive articles not available to anyone else.