0

we have $.inArray(searchString, array) function in jQuery, but this will look for the exact match of the string in the values present in the array. But how to check the string in the array like indexOf?

For e.g., Let us take the string "mark_zuck" and if the array looks like this, ["mark", "sheryl", "zuck"]. We can do this by using a loop comparing each value in array with the given string like,

for (i=0; i<array.length; i++) {
    searchString.indexOf(array[i]);
}

I'm looking for a better way to implement this. Please help.

2
  • @Archer What do you mean by "parse the array"? Commented Aug 20, 2015 at 10:25
  • I deleted my comments as it turns out I was wrong! atinder has posted a nearly correct solution. Commented Aug 20, 2015 at 10:31

2 Answers 2

1
array.filter(function(a){
  return searchString.indexOf(a) !== -1;
}
Sign up to request clarification or add additional context in comments.

4 Comments

It should be return searchString.indexOf(a) !== -1;
@Archer @ atinder Hey, can you take a look of the fiddle, jsfiddle.net/udhayakumar/3v3288s6. Because it is returning ["sheryl", "zuck"] instead of ["mark", "zuck"]. Am I doing something wrong?
Yes, you've highlighted the reason you need !== -1 at the end. atinder updated the answer to include it, so try what he has above now.
@Archer Oops, I didn't notice that. Sorry and thanks :)
0

You can use array.some also

var monthNames = ["mark", "sheryl", "zuck"];
var chk = 'mark_zuck';

var test = monthNames.some(function(e) {    
   return chk.indexOf(e);
});
console.log(test);

Fiddle: http://jsfiddle.net/haqk2snr/

Comments

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.