如何将正则表达式包含到字符串数组中

How to include a regex into an array of strings?

本文关键字:字符串 数组 包含 正则表达式      更新时间:2023-09-26

我有一个函数,它根据url的最后一部分返回HTML class

const currentPage = this.$route.path
const pinkPages = [ '/', '/forgot-pass', '/reset-pass' ]
if (pinkPages.indexOf(currentPage) > -1) return 'footer-pink'

它工作得很好,问题是/reset-pass实际上在末尾有更多的字符。例如,/reset-pass/123

当URL是/reset-pass/1234/reset-pass/abcd或类似的其他模式时,我如何使函数返回footer-pink

也许您想使用正则表达式来尝试与当前页面匹配?

console.log(matchWith('/forgot-pass'));
console.log(matchWith('/reset-pass/'));
console.log(matchWith('/reset-pass/toto'));
console.log(matchWith('/another'));
function matchWith(page) {
  var regex = /(^'/$|'/forgot-pass$|'/reset-pass'/(.*))/
    if(page.match(regex))
      return true
    return false
}
// for your sample
if(matchWith(this.$route.path)) {
   return 'footer-pink';
}

看看这个笨蛋,也许这就是你的答案:https://plnkr.co/edit/sC5VCadDLlRJwH6rpB1T?p=preview

您可以以字符串格式存储正则表达式,然后创建正则表达式数组。

var arr = ["test", "foo", "test2", "bar", "test3"];
var reg_str = ["^test", "o$"];
var regex_list = reg_str.map(function(r) {
  return new RegExp(r);
})
var filtered_list = arr.filter(function(item) {
  return regex_list.filter(function(r) {
    return r.test(item);
  }).length > 0;
});
console.log(filtered_list);