TianRB TianRB - 1 year ago 195
Javascript Question

Find occurrences of string on array - JQuery

I need to find occurrences of a string on an array on the client side.
The examples on the JQuery Docs all use number comparisons, for some reason.

Basically I'm trying to do what in the Terminal is as easy as

grep pattern < file.txt
, but have the data come from an array instead of a file.

This is my code so far. Won't be much help but it'll give you an idea of how I try to accomplish this.

var array = [
'item 1 shalala',
'this is other item',
'more examples',

$( "#submit" ).keydown(function( event ) {
//console.log( "Handler for .keydown() called." );
var result = $.grep(array, function(value, i){
// No idea what to do.
// Will write the array elements that contain the pattern on a div using $('#divId').text(results);

I usually work on lower level languages, I hope the answer is not too obvious.
EDIT: #submit is on an input text field.

Answer Source

indexOf() will search for a substring in a string, it returns its position when found, or -1 when not found.

var result = $.grep(array, function(value) {
    return value.indexOf(pattern) != -1;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download