Skip to content Skip to sidebar Skip to footer

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 c

Solution 1:

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

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

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

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

Solution 2:

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'){
        returnfalse;
    }
    for(var i=0;i<str.length;i++){
        if(str.charCodeAt(i)>127){
            returnfalse;
        }
    }
    returntrue;
}

Solution 3:

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

Solution 4:

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

Post a Comment for "Javascript & Regex : How Do I Check If The String Is Ascii Only?"