Alexandre Cruz
Alexandre Cruz

Reputation: 25

How can I perform a "like" or "contains" search on a string?

Can I compare an especific value of an array in a if() conditional ?

Ex.:

// teacher object
function Prof(id,tab,nome,ocupacao,email,tel,foto)
{
   this.id  = id;
   this.tab = tab;
   this.nome    = nome;
   this.ocupacao= ocupacao;
   this.email   = email;
   this.tel = tel;
   this.foto    = foto;
}

//teachers array
var arr = new Array();
arr[0]  = new Prof('pf1','dir','Mario','Diretor','[email protected]','tel','foto');
arr[1]  = new Prof('pf2','dir','Joao','t1 t3 t7','...','...','...');
...

// So now i will get the array value of "ocupacao" and see if this value has
// an specific value that i´ve defined in the conditional:
...
if(arr[i].ocupacao (has value) t7)
{
    //do something
}

NOTE; There is something that i can use like in PHP or ASP: "LIKE" or "%value%"?

Upvotes: 1

Views: 914

Answers (2)

Jack
Jack

Reputation: 133577

I guess you are referring to the ocupacao array but you inherently mean the ocupacao string that is made by many words separated by spaces..

Then you could do it in three ways:

  • either with regular expression matching withing the string
  • either by splitting the string into a real array and then check if it contains what you need (actually jQuery has a shorthand which is $.inArray(...) otherwise you will have to loop through the array and search for it
  • (forgot to add) Array.indexOf which will return -1 if item is not found

Upvotes: 1

Gaurav
Gaurav

Reputation: 28755

if(arr[i].ocupacao.indexOf('t7') >= 0)
{
   // do something
}

Upvotes: 6

Related Questions