检查多个单词

编程入门 行业动态 更新时间:2024-10-09 02:22:18
本文介绍了检查多个单词的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时送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:关键词]

本文发布于:2023-04-30 22:13:18,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1400872.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:多个   单词

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!