2011-03-03 118 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; 
} 
相關問題