Search code examples
javascriptjqueryregexreplacehref

jQuery replace href value but only partially?


Possible Duplicate:
Change href parameter using jQuery

I have a page with several links like this:

<a href="playcats.php?cat='.$catname.'&sl=10" class="golink">

So after PHP page loads it will look like:

<a href="playcats.php?cat=blue&sl=10" class="golink">
<a href="playcats.php?cat=red&sl=10" class="golink">
<a href="playcats.php?cat=yellow&sl=10" class="golink">
...

I want partially change the href for the sl value of all links using jQuery (sl value is picked from a slider = data.value)

I have this:

$(document).ready(function() {
  $('a.golink').each(function() {
    var _href = $(this).attr('href'); 
    $(this).  ( rest of code.. )
  } );
});

And now I do not know how to use replace with regular expressions as I think it is the solution!


Solution

  • You might do

     $(this).attr('href', _href.replace(/sl=[^&]+/, 'sl=newval'));
    

    to replace the value of sl by 'newval'.

    You can also use a function to build the new value. For example, say you want to multiply by 2 the old sl value, you may do this :

     $(this).attr('href', _href.replace(/sl=([^&]+)/, function(_, oldval) {
          return 'sl='+(2*parseInt(oldval,10))
     }));
    

    You may even avoid using each :

    $('a.golink').attr('href', function(i, v){
      return v.replace(/sl=([^&]+)/, function(_, oldval) {
          return 'sl='+(2*parseInt(oldval,10))
      })
    });
    

    Demonstration (over the links to see the href)