Jump to content

vars in regex


Obi1-Cannabis

Recommended Posts

Im trying to find matches of an inputed text in a list of anchors and scroll to where you can see that match, so what i have and sort of working is this (using jquery):

$("#inputEstabelecimentos").bind("keyup", function(e){   $(".estabelecimentosLink").removeClass('back');   if($("#inputEstabelecimentos").val() != '')   {	  text = $("#inputEstabelecimentos").val();	  text = text.replace(/&/g, '&');						  var re = new RegExp(text, "i");						  $(".estabelecimentosLink").each(		 function()	 {			if($(this).html().search(re)!=-1)			{		   $(this).addClass('back');		   $('#listaEstabelecimentos').scrollTo($(this));		   return false;		}	 }	  );   }   else   {	  $('#listaEstabelecimentos').scrollTo(0);   }});

the problem i have with this piece of code is that it matches anywehere inside the anchor and i want it to match only if at the beginning. So if I write "pen" I want it to match "pencil" but not "some pen".I also know i should have ^ at the beginning of the regex but i can't seem to find a way to do it using the string var inside the expression.

Link to comment
Share on other sites

Here's the test I ran:base = "pen";re = new RegExp("^" + base, "i");s="pencil";s.search(re); // returns 0s="spend";s.search(re); // returns -1So the technique works. I suspect other stuff is mucking it up. You might try using match instead of search. I mean something like:if($(this).html().match(re) )And you can treat it like a Boolean.If that's no help, try alerting the value of $(this).html() to see what it really returns. If it looks like a string, try assigning $(this).html() to a variable, and then using the search/match method of that variable.

Link to comment
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...