Charles
Charles

Reputation: 115

How do I use the .match javascript method to search an array versus a string?

This is a simple way of using the .match method to search through a string and then return whether or not a match was found.

    var match = "hello joe, how are you?".match('joe');

    if (match) {
      console.log(match[0]);
    } else {
      console.log('no match found : (');
    }

When trying to use the .match method to search through an array for particular string – I cannot get a return. Any advice?

var array = ['charlie','jeff','joe'].match('jeff');

if (array) {
  console.log(array[0]);
} else {
  console.log('no dice');
}

Upvotes: 0

Views: 61

Answers (1)

Scimonster
Scimonster

Reputation: 33399

.match() is a JavaScript string method, not array. In your example, you want to use the array .indexOf() method. It returns the index (location) of a specific item in the array, which you can then use to get that item. I recommend reading the documentation (MDN linked above) for more usage information.

var array = ['charlie','jeff','joe'];

if (array.indexOf('jeff') > -1) {
  console.log(array[array.indexOf('jeff')]);
} else {
  console.log('no dice');
}

Upvotes: 1

Related Questions