匹配javascript中的特定字符

时间:2014-04-03 17:16:31

标签: javascript regex

我有一个字符串,我想检查它是否只包含允许的字符。

允许只有字母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");
}

我该怎么做?是否有正则表达式可以帮助我?不幸的是,我没有正则表达式的经验。

1 个答案:

答案 0 :(得分:3)

是的,有正则表达式:

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