用于检测非ascii字符的Javascript正则表达式

时间:2011-03-03 19:12:10

标签: javascript regex

我们如何使用java脚本限制在特定文本字段中使用非ascii字符..?提前谢谢......

2 个答案:

答案 0 :(得分:17)

Ascii被定义为000-177(八进制)范围内的字符,因此

function containsAllAscii(str) {
    return  /^[\000-\177]*$/.test(str) ;
}

http://jsfiddle.net/V5e4B/1/

您可能不想接受非打印字符\000-\037,也许您的正则表达式应为/\040-\0176/

答案 1 :(得分:1)

我来到这个页面试图寻找一个函数来清理一个字符串,用作CMS系统中的友好URL。 CMS是多语言的,但我想阻止非ascii字符出现在URL中。因此,我只是使用(基于上面的解决方案)而不是使用范围:

function verify_url(txt){
    var str=txt.replace(/^\s*|\s*$/g,""); // remove spaces
    if (str == '') {
        alert("Please enter a URL for this page.");
        document.Form1.url.focus();
        return false;
    }
    found=/^[a-zA-Z0-9._\-]*$/.test(str); // we check for specific characters. If any character does not match these allowed characters, the expression evaluates to false
    if(!found) {
        alert("The can only contain letters a thru z, A thru Z, 0 to 9, the dot, the dash and the underscore. No spaces, German specific characters or Chinese characters are allowed. Please remove all punctuation (except for the dot, if you use it), and convert all non complying characters. In German, you may convert umlaut 'o' to 'oe', or in Chinese, you may use the 'pinyin' version of the Chinese characters.");
        document.Form1.url.focus();
    }
    return found;
}