JavaScript &正则表达式:如何检查字符串是否仅为 ASCII? [英] JavaScript & regex : How do I check if the string is ASCII only?

查看:113
本文介绍了JavaScript &正则表达式:如何检查字符串是否仅为 ASCII?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道我可以通过像这样在正则表达式中应用 W 来验证带有单词(0-9 A-Z a-z 和下划线)的字符串:

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

但是如何检查字符串是否仅包含 ASCII 字符?(我想我已经接近了,但我错过了什么?)

But how do I check whether the string contains ASCII characters only? ( I think I'm close, but what did I miss? )

参考:https://stackoverflow.com/a/8253200/188331

UPDATE :标准字符集对我来说已经足够了.

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

或者如果您想使用扩展的 ASCII 字符集:

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

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

这篇关于JavaScript &正则表达式:如何检查字符串是否仅为 ASCII?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆