最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - jQuery - Return all objects in an array that contain a text string - Stack Overflow

programmeradmin3浏览0评论

Is it possible to search an array for a string of text, then return the contents of the objects which contain it?

For example:

<script>
    var itemsArray = ["2Bedroom Ensuite 2Bathroom", "1Bedroom Ensuite 1Bathroom", "3Bedroom 2Bathroom"];
    var searchTerm = 'ensuite';
    var results = $.searchThing('itemsArray', searchTerm);
    document.write(results);
</script>

The above hypothetical script (where 'searchThing' is the method - if it exists) should write

2Bedroom Ensuite 2Bathroom
2Bedroom Ensuite 2Bathroom

Does this exist? How can it be done?

Thanks

Is it possible to search an array for a string of text, then return the contents of the objects which contain it?

For example:

<script>
    var itemsArray = ["2Bedroom Ensuite 2Bathroom", "1Bedroom Ensuite 1Bathroom", "3Bedroom 2Bathroom"];
    var searchTerm = 'ensuite';
    var results = $.searchThing('itemsArray', searchTerm);
    document.write(results);
</script>

The above hypothetical script (where 'searchThing' is the method - if it exists) should write

2Bedroom Ensuite 2Bathroom
2Bedroom Ensuite 2Bathroom

Does this exist? How can it be done?

Thanks

Share Improve this question asked Feb 21, 2014 at 20:45 william44ismewilliam44isme 8772 gold badges13 silver badges25 bronze badges 1
  • 1 May I ask you why you're trying to do in jQuery something that could be easily made with vanilla javascript? – Ragnarokkr Commented Feb 21, 2014 at 20:49
Add a ment  | 

3 Answers 3

Reset to default 10

You can use the ES5 Array.prototype.filter method:

var results = itemsArray.filter(function (elem) {
    return elem.toLowerCase().indexOf(searchTerm) > -1;
});

Note that older browsers don't support the .filter() method. For supporting those browsers you can use a polyfill.

edit: You can also use the jQuery $.grep() utility function:

var results = $.grep(itemsArray, function(elem) {
    return elem.toLowerCase().indexOf(searchTerm) > -1;
}); 

This is possible to do in jQuery (sort of), but it isn't necessary to use jQuery. Here's a jQuery solution anyway

var itemsArray = ['asdf','1234'];
var searchTerm = 'asdf';
var results=[];
$.each(itemsArray, function(i,e){
    if(e.indexOf('asdf') > -1)
        results.push(e);
});

I would prefer undefined's solution personally.

try this

var searchTerm = 'ensuite';
var itemsArray = ["2Bedroom Ensuite 2Bathroom", "1Bedroom Ensuite 1Bathroom", "3Bedroom 2Bathroom"];
for(var i=0;i<itemsArray.length;i++){
 var str=itemsArray[i];
  if(str.indexOf(searchTerm ) >= 0){
   //it contains searchterm do something with it.
  }
}
发布评论

评论列表(0)

  1. 暂无评论