2011-03-03 119 views
5

我们如何使用java脚本来限制在特定文本字段中使用非ASCII字符..?在此先感谢...用于检测非ASCII字符的Java脚本正则表达式

+0

是否要将它们移除或替换? – drudge 2011-03-03 19:14:58

+2

Dup:http://stackoverflow.com/questions/3465874/javascript-regex-to-reject-non-ascii-us-characters(我不参与投票) – 2011-03-03 19:15:07

+0

@jnpcl只需提醒用户即可。 .....删除它们也是一个不错的选择 – sasidhar 2011-03-03 19:15:55

回答

16

ASCII是指在000-177(八进制)范围内的字符,因此

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

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

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

+2

如果所有你想要的是一个布尔值,你应该使用'.test()'而不是'.exec()' - 它直接产生一个布尔值,而不是构建一个匹配对象,然后必须被转换为布尔值。 – 2011-03-03 20:02:59

+0

感谢Ben,我懒得找到正确的方法。根据你的建议修正 – 2011-03-03 20:05:12

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; 
} 
相关问题