0

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 :

  1. 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 ?

  1. 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 )
Community
  • 1
  • 1
mrid
  • 5,782
  • 5
  • 28
  • 71

1 Answers1

1

This function is your 'regex idea' coded in a for-loop:

function isSubstring (input, text) {
    input = input.toLowerCase();
    text = text.toLowerCase();
    var found = 0;
    var nextChar = input.charAt(found);
    for (var i=0, l=text.length; i<l; i++) {
        if (text.charAt(i) === nextChar) {
            found++;
            if (found === input.length)
                return true;
            nextChar = input.charAt(found);
        }
    }
};

Basically, it will look for a substring with zero or more characters between each matched letter:

isSubstring('BZL', 'Brazil');  // true
//                  ^  ^ ^

Then, your code will look like:

var matchdata = function(text_to_match, item_array) {
    var result = item_array.map(function(item, index) {
        if (isSubstring(text_to_match, item)) {
            return [item, index];
        }
        return 0;
    });
    return result.filter(isNaN);
};

The result will be a matrix:

matchdata('bzl', ['BraZiL', 'LiZarB', 'BraZiL']);
// [ ['brazil', 0], ['brazil', 2] ]

Hope it helps :)

Washington Guedes
  • 4,254
  • 3
  • 30
  • 56