如何将正则表达式包含到字符串数组中
How to include a regex into an array of strings?
我有一个函数,它根据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);
相关文章:
- 将JSON转换为typescript中的字符串数组
- 在Javascript中将一个值和字符串数组转换为if语句
- 如何将正则表达式包含到字符串数组中
- JavaScript:将字符串数组转换为文本区域
- Knockout中的字符串数组
- 拆分字符串数组(JavaScript)后未定义
- 使用Javascript获取两个字符串之间的字符串数组
- 打印从Spring MVC Controller发送的字符串数组只显示“;toJSON”;在javascript中
- 将一个字符串数组解析为一个新的数组javascript
- AngularJS - 从字符串数组中连续更改文本
- 使用字符串数组中的字符填充 HTML 表
- 如何在 Javascript 中将字符串数组列表插入到表行中
- 创建二维字符串数组
- 如何从字符串数组中获取子字符串数组
- 如何将字符串数组转换为简单数组
- 按字母顺序、数字顺序和特殊字符对字符串数组进行排序
- 如何从字符串数组中获得8个随机唯一元素
- json_encode($myVar);正在给出地图,我想要一个字符串数组
- 函数,返回javascript中两个字符串数组的差值
- Javascript字符串数组转换为用逗号分隔的多个字符串