0

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 ?

1
  • using regex would be an overkill for this simple problem.. Commented Apr 21, 2013 at 18:32

2 Answers 2

4
<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

Sign up to request clarification or add additional context in comments.

Comments

2

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.)

2 Comments

Snap! :) Extra time required for fiddling :P
@pandit - I don't think a regex would buy you anything in terms of performance or clarity of code. Since searchquery is a variable, quite the opposite, I would think. Also, I added a link to documentation for the filter function.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.