javascript正则表达式在数组上匹配以查找多个项

javascript regex match on array to find multiple items

本文关键字:查找 正则表达式 数组 javascript      更新时间:2023-09-26

是否可以对数组进行正则表达式匹配,以查找包含特定字母的所有项?

我的阵列是:

var myArray = [
    "move",
    "mind",
    "mouse",
    "mountain",
    "melon"
];

我需要找到所有包含字母的项目:"mo",使用类似这样的正则表达式匹配:

/mo'w+/igm

要输出这些单词:"移动"、"鼠标"、"山"。。。

我试过这个,但不能正常工作,它只输出一个项目。。

Array.prototype.MatchInArray = function(value){
    var i;
    for (i=0; i < this.length; i++){
        if (this[i].match(value)){
            return this[i];
        }
    }
    return false;
};
console.log(myArray.MatchInArray(/mo/g));

你甚至不需要RegEx,你可以简单地使用Array.prototype.filter,就像这个

console.log(myArray.filter(function(currentItem) {
    return currentItem.toLowerCase().indexOf("mo") !== -1;
}));
# [ 'move', 'mouse', 'mountain' ]

JavaScript字符串有一个名为String.prototype.indexOf的方法,它将查找作为参数传递的字符串,如果找不到,它将返回-1,否则返回第一个匹配的索引。

编辑:你可以用Array.prototype.filter重写你的原型函数,就像这个

Object.defineProperty(Array.prototype, "MatchInArray", {
    enumerable: false,
    value: function(value) {
        return this.filter(function(currentItem) {
            return currentItem.match(value);
        });
    }
});

这样你就能拿到所有的火柴。这是因为,如果正则表达式与当前字符串不匹配,那么它将返回null,这在JavaScript中被认为是错误的,因此字符串将被过滤掉。

注意:从技术上讲,MatchInArray函数的作用与Array.prototype.filter函数相同。因此,最好利用内置的filter本身。