0

I'm using this code to get items that match a particular keyword.

var match_data = function(search_str, items) {
    var reg = new RegExp(search_str.split('').join('\\w*').replace(/\W/, ""), 'i');
    return items.filter(function(item_data) {
        if (item_data.match(reg)) {
            return item_data;
        }
    });
};

Is there any way I can get the index of the matched item as well ?

Also I keep getting this warning when my search string comtains \ anywhere in it:

Uncaught SyntaxError: Invalid regular expression: /iw*m\w*\/: \ at end of pattern(…)

Can you guys please help me solve this error as well.

Thanks in advance.

4
  • 1
    please add some data and the wanted result. Commented Nov 6, 2016 at 9:57
  • filter expect a boolean value, not the value of the item, if it should be inserted into the result set. Commented Nov 6, 2016 at 9:58
  • About index: you can use indexOf(val) function to get the index of value from the array. Commented Nov 6, 2016 at 9:59
  • 1
    @rakaz, this method won't work if you have 2 items with the exact same text in the list ( eg. var list = [ 'abc', 'def', 'abc', 'efg' ] ) Commented Nov 6, 2016 at 10:03

1 Answer 1

2

You could use another array and the index from the callback API of Array#filter.

var match_data = function(search_str, items) {
        var reg = new RegExp(search_str.split('').join('\\w*').replace(/\W/, ""), 'i'),
            indices = [];

        return {
            result: items.filter(function(item_data, index) {
                if (item_data.match(reg)) {
                    indices.push(index);
                    return true;
                }
            }),
            indices: indices
        };
    };
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks :) I'll give this a try and let you know

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.