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

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 true and hasMoreThanAscii2 is false.

Conclusion

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