简体   繁体   中英

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

I know I can validate against string with words ( 0-9 AZ az and underscore ) by applying W in regex like this:

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? )

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

UPDATE : Standard character set is enough for my case.

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:

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

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:

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;
}

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

Supported browsers:

  • Chrome 64+
  • Safari/JavaScriptCore beginning in Safari Technology Preview 42
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;
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM