jquery - Get item index when using filter in javascript -
i'm using code items match 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 way can index of matched item ?
also keep getting warning when search string comtains \
anywhere in it:
uncaught syntaxerror: invalid regular expression: /iw*m\w*\/: \ @ end of pattern(…)
can guys please me solve error well.
thanks in advance.
you use array , index 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 }; };
Comments
Post a Comment