[英]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:我知道我可以通过在正则表达式中应用W
来验证带有单词(0-9 AZ az 和下划线)的字符串,如下所示:
function isValid(str) { return /^\w+$/.test(str); }
But how do I check whether the string contains ASCII characters only?但是如何检查字符串是否仅包含 ASCII 字符? ( I think I'm close, but what did I miss? ) (我想我已经接近了,但我错过了什么?)
Reference: https://stackoverflow.com/a/8253200/188331参考: 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:或者,如果您想使用扩展的 ASCII 字符集:
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:您不需要 RegEx 来执行此操作,只需检查该字符串中的所有字符是否都具有介于 0 和 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.对于 ES2018,Regexp 支持Unicode 属性转义,您可以使用/[\\p{ASCII}]+/u
来匹配 ASCII 字符。 It's much clear now.现在已经很清楚了。
Supported browsers:支持的浏览器:
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;
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.