我们如何使用javascript在数组中使用正则表达式过滤数组中的元素? [英] how can we filter elements in array with regex in array with javascript?

查看:18
本文介绍了我们如何使用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'
]

嗯,我当时的想法是做一些类似 reduce 的事情:

Well, what I was thinking was to do something like reduce:

// 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);
    });
});

但实际上,除非您执行 10,000 次,否则这里的性能差异可以忽略不计.

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天全站免登陆