【问题标题】:Check if an item of an array is in a string using Regex in JavaScript使用 JavaScript 中的正则表达式检查数组的项目是否在字符串中
【发布时间】:2020-08-06 05:12:29
【问题描述】:

我需要一些用于 Vue 应用程序的简单 javascript 代码,它将一个字符串拆分为一个数组并检查是否有任何值在不同的字符串中。

我有

              let AffiliationString = " This person goes to Stony Brook"

              let affiliation = "Stony Brook OR Stony Brook University OR The University of Washington"
              let affiliations = affiliation.toLowerCase().split(" or ");
              affiliation = affiliations.join(",");
               let regexList = [ affiliation ];

               let isMatch = regexList.some(rx => rx.test(AffiliationString));

我想看看数组中是否有任何项目在“AffiliationString”字符串中

当我这样做时,我得到以下错误

       Uncaught (in promise) TypeError: rx.test is not a function

我在 StackOverflow 上看到了许多检查数组是否存在值的示例,但反之则不然。 我正在尝试使用 javascript - match regular expression against the array of items

我在一个 Vue 项目中使用

         "eslint": "6.7.2",

我需要为数组中的每个值重做一个循环吗?

感谢您的帮助

【问题讨论】:

    标签: javascript vue.js es6-promise


    【解决方案1】:

    您实际上并没有从您的affiliation 字符串中生成RegExp,这就是为什么rx.test 不是函数的原因。您可以创建一个RegExp,它会一次匹配所有附属字符串片段,方法是用| 分隔它们。我们将正则表达式中的每个元素包装在\b 中,以便(例如)BrookBrooktown 不匹配。将i 标志添加到RegExp 使其不区分大小写:

    let AffiliationString = " This person goes to Stony Brook"
    let affiliation = "Stony Brook OR Stony Brook University OR The University of Washington"
    let regex = new RegExp('\\b' + affiliation.split(/\s+or\s+/i).join('\\b|\\b') + '\\b', 'i')
    let isMatch = regex.test(AffiliationString)
    console.log(isMatch)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-03-19
      • 2017-04-15
      • 1970-01-01
      • 2023-04-01
      • 2021-09-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多