JavaScript检查字符串是否包含正则表达式中的任何单词
我正在尝试检查字符串是否包含以下单词:JavaScript检查字符串是否包含正则表达式中的任何单词,javascript,regex,Javascript,Regex,我正在尝试检查字符串是否包含以下单词: AB|AG|AS|Ltd|KB|University 我当前的代码: var acceptedwords = '/AB|AG|AS|Ltd|KB|University/g' var str = 'Hello AB'; var matchAccepted = str.match(acceptedwords); console.log(matchAccepted); if (matchAccepted !== null) { // Contains th
AB|AG|AS|Ltd|KB|University
我当前的代码:
var acceptedwords = '/AB|AG|AS|Ltd|KB|University/g'
var str = 'Hello AB';
var matchAccepted = str.match(acceptedwords);
console.log(matchAccepted);
if (matchAccepted !== null) { // Contains the accepted word
console.log("Contains accepted word: " + str);
} else {
console.log("Does not contain accepted word: " + str);
}
但出于某种奇怪的原因,这并不匹配
知道我做错了什么吗?这不是定义文字的正确方法 改变
var acceptedwords = '/AB|AG|AS|Ltd|KB|University/g'
到
你可能会注意到我删除了g标志:这是没有用的,因为你只想知道是否有一个匹配,你不想得到所有匹配。您甚至不必在这里使用match
,您可以使用test
:
var str = 'Hello AB';
if (/AB|AG|AS|Ltd|KB|University/.test(str)) { // Contains the accepted word
console.log("Contains accepted word: " + str);
} else {
console.log("Does not contain accepted word: " + str);
}
如果您想构建一个带有字符串的正则表达式,假设其中没有一个包含任何特殊字符,您可以这样做
var words = ['AB','AG', ...
var regex = new RegExp(words.join('|'));
如果您的姓名可能包含特殊字符,则必须使用
如果你不想让你的单词成为其他单词的一部分(意思是你不想匹配“ABC”),那么你应该检查单词边界:
regex = new RegExp(words.map(function(w){ return '\\b'+w+'\\b' }).join('|'),'g');
我能在/myVarHere/g之间插入一个字符串吗?@Alosyius请看构造函数。@Alosyius:太棒了!尽快接受:)@dystroy接受的单词不需要被单词边界包围,
\b
否则,当接受的单词出现在其他单词中时,您可以获得匹配。请参见此处:newregexp('AB | AG | AS | Ltd | KB | University','g')
或/AB | AG | AS | Ltd | KB | University/g
,但不是两者的组合:)
regex = new RegExp(words.map(function(w){ return '\\b'+w+'\\b' }).join('|'),'g');