JavaScript & regex : How do I check if the string is ASCII only?
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;
}