Anshul
Anshul

Reputation: 9480

How can I search a string from a string array in javascript?

I have a string 'a' and want all results which have 'a' string array.

var searchquery = 'a';
var list = [temple,animal,game,match, add];

I want result = [animal,game,match,add]; all elements which have 'a' as a part of their name.how can I achieve that ?

Upvotes: 0

Views: 67

Answers (2)

Ted Hopp
Ted Hopp

Reputation: 234795

You can filter the list:

var searchquery = 'a';
var list = ['temple', 'animal', 'game', 'match', 'add'];
var results = list.filter(function(item) {
    return item.indexOf(searchquery) >= 0;
});
// results will be ['animal', 'game', 'match', 'add']

(Note that you need to quote the strings in the list array.)

Upvotes: 2

Xotic750
Xotic750

Reputation: 23472

<div id="display"></div>

var searchquery = 'a';
var list = ["temple", "animal", "game", "match", "add"];
var results = list.filter(function(item) {
    return item.indexOf(searchquery) >= 0;
});

document.getElementById("display").textContent = results.toString();

on jsfiddle

Upvotes: 4

Related Questions