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.
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.
Share Improve this question edited Aug 9, 2013 at 13:01 Jon Adams 25.2k18 gold badges84 silver badges121 bronze badges asked Jul 12, 2013 at 2:48 pmark019pmark019 1,2095 gold badges16 silver badges24 bronze badges 3- stackoverflow./questions/784012/… Does this help? – Ariane Commented Jul 12, 2013 at 2:51
- 2 Is it the iteration through the array of the string dissection that you're having problems with? What have you tried? – DevlshOne Commented Jul 12, 2013 at 2:53
- 1 Array.filter – Matt Burland Commented Jul 12, 2013 at 2:54
5 Answers
Reset to default 3Check 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;
});
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);
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./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;
}
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 plex
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