1

How can I find whether a keyword exists in an array which was splitted with split()?

// Get the object infomation.
var keyword = 'story';
var path = $(this).find('a').attr('href');
var array_url = path.split('/');

if(keyword == array_url) alert('match!'); // does it work like this??

The url path from a tag is something like this - www.mysite.com/story/article-1

Thanks.

EDIT:

if ($.inArray(keyword, array_url)) alert('match!');

this will alert the match whether the array has the keyword in it or not.

Run
  • 54,938
  • 169
  • 450
  • 748
  • sounds similar to : http://stackoverflow.com/questions/143847/best-way-to-find-an-item-in-a-javascript-array – JMax Jun 23 '11 at 15:43

3 Answers3

2

if(keyword == array_url) alert('match!'); // does it work like this??

Well, does it? ;)

jQuery has a convenience function for searching through arrays.

if ( $.inArray(keyword, array_url) > -1 ) alert('match!)';

Or, in your case, you could use regular JavaScript string operations:

if ( $(this).find('a').attr('href').indexOf(keyword) > -1 ) alert('match!)';
Tomalak
  • 332,285
  • 67
  • 532
  • 628
  • thanks. see my edit above. but the regular JavaScript string operations works fine. why not jquery? – Run Jun 23 '11 at 15:54
  • @lauthiamkok: There's nothing wrong with using jQuery. It's just that splitting a string into an array and then searching through the array for what's basically nothing more than a "partial string match" is kinda complicated – Tomalak Jun 23 '11 at 16:20
  • 1
    I think this is how to do it in jquery method as Dogbert says, `if ($.inArray(keyword, array_url) != -1) alert('match!');` thanks! :-) – Run Jun 23 '11 at 16:21
1

jQuery.inArray returns -1 if match is not found.

You should do

if ($.inArray(keyword, array_url) != -1) alert('match!');
Dogbert
  • 212,659
  • 41
  • 396
  • 397
0

See http://api.jquery.com/jQuery.inArray/

if ($.inArray(keyword, array_url) > -1) alert('match!');

js1568
  • 7,012
  • 2
  • 27
  • 47