问题描述
限时送ChatGPT账号..当我向 titleIs Var 添加一个以上的单词时,这段代码有一个问题,它不会触发 if 语句.上面的那个不起作用,即如果一个单词在 Var titleIs 中并且在 var words 中,则触发 if 语句.
I have one problem with this code when I add more than one word to the titleIs Var it does not fire the if statement. The top one does not work ie if a word is in Var titleIs and is in var words, fire the if statement.
感谢您的帮助!
var titleIs = ['Knit', 'Main'];
var words = ['Woven', 'Main'];
var regex = new RegExp('^(' + words.join('|') + ')$');
if (regex.test(titleIs)) {
alert("true")
}
这两个工作:
var titleIs = ['Woven'];
var words = ['Woven', 'Main'];
var regex = new RegExp('^(' + words.join('|') + ')$');
if (regex.test(titleIs)) {
alert("true")
}
var titleIs = ['Main'];
var words = ['Woven', 'Main'];
var regex = new RegExp('^(' + words.join('|') + ')$');
if (regex.test(titleIs)) {
alert("true")
}
推荐答案
test
方法接受单个字符串.(实际上,当您发送一个只有一个元素的数组时,它会考虑该元素).
test
method accepts a single string. (in fact when you send an array with only one element, it takes that element into account).
您需要像这样定义一个名为 testAny
的新方法:
You need a new method called testAny
to be defined like this:
RegExp.prototype.testAny = function (arr){
for(var i=0; i<arr.length; i++){
if (this.test(arr[i])) return true;
}
return false;
}
(实际上 matchesAny
是一个更好的名字 - 在我看来 - 但使用上面的名字是为了与现有的 test
方法保持一致)
(in fact matchesAny
is a better name - in my opinion - but used the above name to keep it consistent with the existing test
method)
然后在您的 if
中使用.
and then be used in your if
instead.
if(regex.testAny(titleIs)) ...
这篇关于检查多个单词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
更多推荐
[db:关键词]
发布评论