在 JavaScript 中使用正则表达式检查数组的一项是否在字符串中

Check if an item of an array is in a string using Regex in JavaScript

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

我有

              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

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

我在一个 Vue 项目中使用

         "eslint": "6.7.2",

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

感谢您的帮助

您实际上并没有从 affiliation 字符串中生成 RegExp,这就是 rx.test 不是函数的原因。您可以制作一个 RegExp 来同时匹配所有从属关系字符串片段,方法是用 | 分隔它们。我们将正则表达式中的每个元素包装在 \b 中,以便(例如)Brook 不匹配 Brooktown。将 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)