簡體   English   中英

javascript正則表達式匹配數組以查找多個項目

[英]javascript regex match on array to find multiple items

是否可以對數組進行正則表達式匹配以查找包含某些字母的所有項?

我的數組是:

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

我需要使用正則表達式匹配來查找包含字母“ mo”的所有項目:

/mo\w+/igm

輸出這些詞: “ move”,“ mouse”,“ mountain” ...

我已經嘗試過了,但是不能正常工作,它只能輸出一項。

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本身。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM