JavaScript 和正则表达式:如何检查字符串是否仅为 ASCII?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14313183/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 16:20:43  来源:igfitidea点击:

JavaScript & regex : How do I check if the string is ASCII only?

javascriptregex

提问by Raptor

I know I can validate against string with words ( 0-9 A-Z a-z and underscore ) by applying Win regex like this:

我知道我可以通过W在正则表达式中应用这样的单词(0-9 AZ az 和下划线)来验证字符串:

function isValid(str) { return /^\w+$/.test(str); }

But how do I check whether the string contains ASCII characters only? ( I think I'm close, but what did I miss? )

但是如何检查字符串是否仅包含 ASCII 字符?(我想我已经接近了,但我错过了什么?)

Reference: https://stackoverflow.com/a/8253200/188331

参考:https: //stackoverflow.com/a/8253200/188331

UPDATE: Standard character set is enough for my case.

更新:标准字符集对我来说就足够了。

回答by zzzzBov

All you need to do it test that the characters are in the right character range.

您只需要测试字符是否在正确的字符范围内即可。

function isASCII(str) {
    return /^[\x00-\x7F]*$/.test(str);
}

Or if you want to possibly use the extended ASCII character set:

或者,如果您想使用扩展的 ASCII 字符集:

function isASCII(str, extended) {
    return (extended ? /^[\x00-\xFF]*$/ : /^[\x00-\x7F]*$/).test(str);
}

回答by Danilo Valente

You don't need a RegEx to do it, just check if all characters in that string have a char code between 0 and 127:

您不需要 RegEx 来执行此操作,只需检查该字符串中的所有字符是否都具有介于 0 和 127 之间的字符代码:

function isValid(str){
    if(typeof(str)!=='string'){
        return false;
    }
    for(var i=0;i<str.length;i++){
        if(str.charCodeAt(i)>127){
            return false;
        }
    }
    return true;
}

回答by Kevin Yue

For ES2018, Regexp support Unicode property escapes, you can use /[\p{ASCII}]+/uto match the ASCII characters. It's much clear now.

对于 ES2018,Regexp 支持Unicode 属性转义,可以/[\p{ASCII}]+/u用来匹配 ASCII 字符。现在已经很清楚了。

Supported browsers:

支持的浏览器:

  • Chrome 64+
  • Safari/JavaScriptCore beginning in Safari Technology Preview 42
  • 铬 64+
  • 从 Safari Technology Preview 42 开始的 Safari/JavaScriptCore

回答by StarPlayrX

var check = function(checkString) {

    var invalidCharsFound = false;

    for (var i = 0; i < checkString.length; i++) {
        var charValue = checkString.charCodeAt(i);

        /**
         * do not accept characters over 127
         **/

        if (charValue > 127) {
            invalidCharsFound = true;
            break;
        }
    }

    return invalidCharsFound;
};