开发者

Java Script regular expression for detecting non-ascii characters

开发者 https://www.devze.com 2023-02-14 12:02 出处:网络
How can we use 开发者_运维百科java script to restrict the use of non-ascii characters in a specific text field..? thanks in advance...Ascii is defined as the characters in the range of 000-177 (octal)

How can we use 开发者_运维百科java script to restrict the use of non-ascii characters in a specific text field..? thanks in advance...


Ascii is defined as the characters in the range of 000-177 (octal), therefore

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

console.log ( containsAllAscii('Hello123-1`11'));
console.log ( containsAllAscii('ábcdé'));

You probably don't want to accept non-printing characters \000-\037, maybe your regex should be /\040-\176/


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. The CMS is multilingual but I wanted to prevent non-ascii characters to appear in the 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;
}
0

精彩评论

暂无评论...
验证码 换一张
取 消