Is possible to do a regex match on an array to find all the items containing certain letters?
My array is:
var myArray = [
"move",
"mind",
"mouse",
"mountain",
"melon"
];
I need to find all items containing the letters: "mo", using a regex match like this:
/mo\w+/igm
To output these words: 'move', 'mouse', 'mountain'...
I've tried this, but does not work properly, it outputs only one item..
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));
1 Answer 1
You don't even need RegEx for this, you can simply use Array.prototype.filter, like this
console.log(myArray.filter(function(currentItem) {
return currentItem.toLowerCase().indexOf("mo") !== -1;
}));
# [ 'move', 'mouse', 'mountain' ]
JavaScript Strings have a method called String.prototype.indexOf, which will look for the string passed as a parameter and if it is not found, it will return -1, otherwise the index of the first match.
Edit: You can rewrite your prototype function, with Array.prototype.filter, like this
Object.defineProperty(Array.prototype, "MatchInArray", {
enumerable: false,
value: function(value) {
return this.filter(function(currentItem) {
return currentItem.match(value);
});
}
});
so that you will get all the matches. This works because, if the regex doesn't match the current string, then it will return null, which is considered as falsy in JavaScript, so that string will be filtered out.
Note: Technically, your MatchInArray function does the same job as Array.prototype.filter function. So, better make use of the built-in filter itself.