javascript 如何判断字符串中是否包含任何非 ASCII 字符?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13522782/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I tell if a string has any non-ASCII characters in it?
提问by wwaawaw
I'm looking to detect internationalized domain names and local portions in email addresses, and would like to know if there is a quick and easy way to do this with regex or otherwise in Javascript.
我希望检测电子邮件地址中的国际化域名和本地部分,并想知道是否有一种快速简便的方法可以使用正则表达式或其他方式在 Javascript 中执行此操作。
回答by alex
This should do it...
这个应该可以...
var hasMoreThanAscii = /^[\u0000-\u007f]*$/.test(str);
...also...
...还...
var hasMoreThanAscii = str
.split("")
.some(function(char) { return char.charCodeAt(0) > 127 });
ES6 goodness...
ES6 天哪...
let hasMoreThanAscii = [...str].some(char => char.charCodeAt(0) > 127);
回答by elclanrs
Try with this regex. It tests for all ascii characters that have some meaningin a string, from space 32
to tilde 126
:
试试这个正则表达式。它测试所有在字符串中具有某种含义的ascii 字符,从空格32
到波浪号126
:
var ascii = /^[ -~]+$/;
if ( !ascii.test( str ) ) {
// string has non-ascii characters
}
Edit:with tabs and newlines:
编辑:使用制表符和换行符:
/^[ -~\t\n\r]+$/;
回答by Nathan Wall
charCodeAt
can be used to get the character code at a certain position in a string.
charCodeAt
可用于获取字符串中某个位置的字符代码。
function isAsciiOnly(str) {
for (var i = 0; i < str.length; i++)
if (str.charCodeAt(i) > 127)
return false;
return true;
}