Obi1-Cannabis Posted November 3, 2010 Share Posted November 3, 2010 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 More sharing options...
jeffman Posted November 3, 2010 Share Posted November 3, 2010 Did you try:new RegExp("^" + text, "i"); Link to comment Share on other sites More sharing options...
Obi1-Cannabis Posted November 3, 2010 Author Share Posted November 3, 2010 Yes i've tried it and it doesn't work.that way it simply doesn't find matches. Link to comment Share on other sites More sharing options...
jeffman Posted November 3, 2010 Share Posted November 3, 2010 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 More sharing options...
jeffman Posted November 3, 2010 Share Posted November 3, 2010 Is it possible that the string you are searching has a non-printing character at the start, like a space, tab, or line break? Link to comment Share on other sites More sharing options...
Obi1-Cannabis Posted November 4, 2010 Author Share Posted November 4, 2010 Is it possible that the string you are searching has a non-printing character at the start, like a space, tab, or line break?Yes that was that was the a problem. thanks Link to comment Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.