gpt4 book ai didi

javascript - 匹配javascript中的特定字符

转载 作者:行者123 更新时间:2023-11-28 19:54:24 25 4
gpt4 key购买 nike

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

仅允许使用字母 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");
}

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

最佳答案

是的,有一个正则表达式:

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

关于javascript - 匹配javascript中的特定字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22844588/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com