简体   繁体   English

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

[英]Java Script regular expression for detecting non-ascii characters

How can we use java script to restrict the use of non-ascii characters in a specific text field..? 我们如何使用java脚本来限制在特定文本字段中使用非ascii字符..? thanks in advance... 提前致谢...

Ascii is defined as the characters in the range of 000-177 (octal), therefore 因此,Ascii被定义为000-177(八进制)范围内的字符

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

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

You probably don't want to accept non-printing characters \\000-\\037 , maybe your regex should be /\\040-\\0176/ 你可能不想接受非打印字符\\000-\\037 ,也许你的正则表达式应该是/\\040-\\0176/

I came accross this page trying to look for a function to sanitize a string to be used as friendly URL in a CMS system. 我来到这个页面试图寻找一个函数来清理一个字符串,用作CMS系统中的友好URL。 The CMS is multilingual but I wanted to prevent non-ascii characters to appear in the URL. CMS是多语言的,但我想阻止非ascii字符出现在URL中。 So instead of using ranges, I simply used (based on the solution above): 因此,我只是使用(基于上面的解决方案)而不是使用范围:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM