如何判断字符串中是否包含任何非ASCII字符?

时间:2021-01-16 19:24:38

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.

我正在寻找检测电子邮件地址中的国际化域名和本地部分,并想知道是否有一种快速简便的方法来使用正则表达式或其他方式在Javascript中执行此操作。

3 个解决方案

#1


12  

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

试试这个正则表达式。它测试所有在字符串中具有某种含义的ascii字符,从空格32到波形126:

var ascii = /^[ -~]+$/;

if ( !ascii.test( str ) ) {
  // string has non-ascii characters
}

Edit: with tabs and newlines:

编辑:使用标签和换行符:

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

#2


19  

This should do it...

这应该做到......

var hasMoreThanAscii = /^[\u0000-\u007f]*$/.test(str);

...also...

...也...

var hasMoreThanAscii = str
                       .split("")
                       .some(function(char) { return char.charCodeAt(0) > 127 });

ES6 goodness...

ES6善良......

let hasMoreThanAscii = [...str].some(char => char.charCodeAt(0) > 127);

#3


9  

charCodeAt can be used to get the character code at a certain position in a string.

charCodeAt可用于获取字符串中某个位置的字符代码。

function isAsciiOnly(str) {
    for (var i = 0; i < str.length; i++)
        if (str.charCodeAt(i) > 127)
            return false;
    return true;
}

#1


12  

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

试试这个正则表达式。它测试所有在字符串中具有某种含义的ascii字符,从空格32到波形126:

var ascii = /^[ -~]+$/;

if ( !ascii.test( str ) ) {
  // string has non-ascii characters
}

Edit: with tabs and newlines:

编辑:使用标签和换行符:

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

#2


19  

This should do it...

这应该做到......

var hasMoreThanAscii = /^[\u0000-\u007f]*$/.test(str);

...also...

...也...

var hasMoreThanAscii = str
                       .split("")
                       .some(function(char) { return char.charCodeAt(0) > 127 });

ES6 goodness...

ES6善良......

let hasMoreThanAscii = [...str].some(char => char.charCodeAt(0) > 127);

#3


9  

charCodeAt can be used to get the character code at a certain position in a string.

charCodeAt可用于获取字符串中某个位置的字符代码。

function isAsciiOnly(str) {
    for (var i = 0; i < str.length; i++)
        if (str.charCodeAt(i) > 127)
            return false;
    return true;
}