trinvh trinvh - 1 year ago 104
Javascript Question

String indexOf always return -1

I'm in stuck while trying to filter an array using Array.filter method.

Please take a look into my code:

$scope.products = CachedData.Products.filter(function (item) {
var itemNameSlug = Helpers.slug(item.Name); // eg: product100
var keywordSlug = Helpers.slug($scope.keyword); // eg: p, pr, pro, duct etc...
var result = itemNameSlug.indexOf(keywordSlug);
console.log(result); // always -1
return result > -1;

When I type keyword as alphabet, it always return empty array (that indexOf return -1). If I type numeric, example is 1 or 10 or 100 or 00, i got correct result.

Why ?

Any help will be appreciated. Thanks

Answer Source

@trinvh according to the output in your comment, you're having a trailing space getting in the middle when searching for the needle in the haystack, if the needle gets a trailing space, it would be impossible to match (since we are dealing here with slugs, which don't contain spaces)

/* according to your comment: */
console.log('-' + itemNameSlug + '-', '-' + keywordSlug + '-', typeof itemNameSlug, typeof keywordSlug);
/* gives: -product95 - -pro - string string */

then I would say the needle is "pro ", which won't match against "product95 "

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download