我们怎么可以过滤用JavaScript数组与正则表达式元素数组? [英] how can we filter elements in array with regex in array with javascript?

查看:633
本文介绍了我们怎么可以过滤用JavaScript数组与正则表达式元素数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

让我们说我有两个数组:一个是正则表达式,另一种是输入。那么,什么是最好的方式 - 在性能和可读性方面 - 做类似的东西输出

Let's say I have two arrays: one is the regex and the other one is the input. What, then, is the best way - in terms of performance and readability - to do something like the output?

var regex = [
    '/rat/',
    '/cat/'
    '/dog/',
    '/[1-9]/'
]

var texts = [
    'the dog is hiding',
    'cat',
    'human',
    '1'
]

最终的结果是

result = [
    'human'
]

那么,我在想是做类似减少

// loop by text
for (var i = texts.length - 1; i >= 0; i--) {
    // loop by regex
    texts[i] = regex.reduce(function (previousValue, currentValue) {
        var filterbyRegex = new RegExp("\\b" + currentValue + "\\b", "g");  
        if (previousValue.toLowerCase().match(filterbyRegex)) {
            delete texts[i];
        };
        return previousValue;
    }, texts[i]);
}

不过,是不是可读?也许有,我没有想到的另一种方式。

But, is that not readable? Maybe there is another way that I haven't thought of.

推荐答案

我可能会是这样的。

var regexs = [
    /rat/i,
    /cat/i,
    /dog/i,
    /[1-9]/i
]

var texts = [
    'the dog is hiding',
    'cat',
    'human',
    '1'
]

var goodStuff = texts.filter(function (text) {
    return !regexs.some(function (regex) {
         return regex.test(text);
    });
});

但实际上,性能差异是如此的微不足道的,除非你正在做10000次。

But realistically, performance differences are so negligible here unless you are doing it 10,000 times.

请注意,这里使用ES5的方法,这很容易shimmable(我做了我所知道的单词)

Please note that this uses ES5 methods, which are easily shimmable (I made up a word I know)

这篇关于我们怎么可以过滤用JavaScript数组与正则表达式元素数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆