pmark019
pmark019

Reputation: 1209

How to check an array if it contains a string in Javascript?

I have an array that contains string.

var js_userBoxName = new Array();

I want to search the elements of the array if a string has the word "foo" it should displayed.

So for example my array contains the words {foofy, foofa, foo, awtsy}, foofy, foofa and foo will be displayed since they all contains the word foo.

Upvotes: 2

Views: 8383

Answers (5)

shigatsu
shigatsu

Reputation: 46

You could also try this:

var myarray = ["foofy", "foofa", "foo", "awtsy"];
var searched_string = "foo"; 
var foundmatch = [];

for(i=0; i < myarray.length; i++){
  if(myarray[i].match(searched_string)){
    foundmatch.push(myarray[i]);
  }
} 

alert(foundmatch); 

Upvotes: 2

Data Crusader
Data Crusader

Reputation: 434

The following should work:

var myArray = ['foofy', 'foofa', 'foo', 'awtsy'];

for ( var i = 0; i < myArray.length; i++ ) {
  if ( myArray[i].contains('foo') )
    console.log(myArray[i]);
}

prints: foofy foofa foo

Note: "awtsy" does not contain the pattern foo

Upvotes: 0

tike
tike

Reputation: 2294

The following function should do the trick, it uses only standard acme script elements

function Find (myarray, searchterm){
    for (var i=0, len = myarray.length; i<len; i += 1){
         if (typeof(myarray[i]) === 'string' && myarray[i].search(searchterm) !== -1){
             // print or whatever
             //hint use a callback here that you pass in as an additional arugment
         }
    }
}

using search allows you to use regex if you need to check for something more complex

Upvotes: 2

Casey Flynn
Casey Flynn

Reputation: 14048

NOTE: Good performance tip is to always cache the length of your array when iterating over it rather than recalculating it for each loop execution. len = js_userBoxName.length

http://jsperf.com/caching-array-length/4

function () {
    for(var i = 0, len = js_userBoxName.length; i < len; i++){
      if(typeof js_userBoxName[i] === 'string'){
        if(js_userBoxName[i].indexOf('foo') == -1)
          return true;
      }
    }
    return false;
}

Upvotes: 2

Andrew Whitaker
Andrew Whitaker

Reputation: 126082

Check out the Array.filter method:

var arr = ['foofy', 'foofa', 'foo', 'awtsy'];
var fooItems = arr.filter(function (item) {
    return item.indexOf('foo') >= 0;
});

// Yields ['foofy', 'foofa', 'foo']

The linked MDN page contains a polyfill for browsers that do not support it. If you happen to be using jQuery, you could use $.grep:

var arr = ['foofy', 'foofa', 'foo', 'awtsy'];
var fooItems = $.grep(arr, function (item) {
    return item.indexOf('foo') >= 0;
});

Upvotes: 3

Related Questions