Raptor
Raptor

Reputation: 54212

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

I know I can validate against string with words ( 0-9 A-Z a-z 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.

Upvotes: 54

Views: 64095

Answers (4)

StarPlayrX
StarPlayrX

Reputation: 53

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

Upvotes: 2

Kevin Yue
Kevin Yue

Reputation: 392

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

Upvotes: 12

zzzzBov
zzzzBov

Reputation: 179046

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

Upvotes: 129

Danilo Valente
Danilo Valente

Reputation: 11342

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

Upvotes: 13

Related Questions