I have seen Return positions of a regex match() in Javascript? but not sure how to implement it in my case
I have an array item_array
and I want to filter all items containing text val
This is the code I'm using :
I have made a function matchdata
to filter the results
var matchdata = function(text_to_match, item_array) {
var reg = new RegExp(text_to_match.split('').join('\\w*').replace(/\W/, ""), 'i');
return item_array.filter(function(item) {
if (item.match(reg)) {
return item;
}
});
};
And I'm using it like
var matching_items = matchdata(val, item_array);
Now I have 2 questions :
- When
val
( item to find in array ) contains more than one\
, it starts giving this error in console :
Uncaught SyntaxError: Invalid regular expression: /\w*\w*/: \ at end of pattern(…)
Why is this happening ? and is there any way to rectify this ?
- Is there any way the
filter
function can return the matched item index along with the matched item ( assuming there can be duplicate entries in the array )