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? )
################### answer ###################
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);
}
0 Response to " JavaScript & regex : How do I check if the string is ASCII only?"
Posting Komentar