且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

JavaScript &正则表达式:如何检查字符串是否仅为 ASCII?

更新时间:2023-02-26 11:25:48

您只需要做的就是测试字符是否在正确的字符范围内.

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