2014-04-03 50 views
0

我有一個字符串,我想檢查它是否只包含允許的字符。匹配javascript中的特定字符

只允許字母a,b,c,d,e,k。我想到了這樣的事情:

var string1 = "abcdekabc" 
if (string1 contains only a,b,c,d,e,k) { 
    document.write("everything is fine"); 
} else { 
    document.write("there is one or more character that is not allowed"); 
} 

我該怎麼做?有一個正則表達式可以幫助我嗎?不幸的是,我沒有使用正則表達式的經驗。

回答

2

是有一個正則表達式:

var pattern = new RegExp('[^abcdek]', 'i'); 
var string1 = "abcdekabc"; 
if(!pattern.test(string1)){ 
    document.write("everything is fine"); 
} else { 
    document.write("there is one or more character that is not allowed"); 
} 

這可以簡化爲:

var string1 = "abcdekabc"; 
if(!(/[^abcdek]/i).test(string1)){ 
    document.write("everything is fine"); 
} else { 
    document.write("there is one or more character that is not allowed"); 
} 

如果你願意,你可以以防萬一走另一條路(不檢查非法字符):

var string1 = "abcdekabc"; 
if((/^[abcdek]+$/i).test(string1)){ 
    document.write("everything is fine"); 
} else { 
    document.write("there is one or more character that is not allowed"); 
} 
相關問題