Search code examples
javascriptregexunicodeascii

How can I tell if a string has any non-ASCII characters in it?


I'm looking to detect internationalized domain names and local portions in email addresses, and would like to know if there is a quick and easy way to do this with regex or otherwise in Javascript.


Solution

  • Try with this regex. It tests for all ascii characters that have some meaning in a string, from space 32 to tilde 126:

    var ascii = /^[ -~]+$/;
    
    if ( !ascii.test( str ) ) {
      // string has non-ascii characters
    }
    

    Edit: with tabs and newlines:

    /^[ -~\t\n\r]+$/;