Search code examples
jqueryhtmlurlencodeampersand

How to encode ampersand in URL with jQuery


I have some URLs being dynamically output onto a div which contain an & like this:

<div id="box">
    <a href="http://domain.com/index.html&location=1">First URL</a> 
    <a href="http://domain.com/index.html&location=2">Second URL</a>
</div>

Is there a way - using jQuery - for every instance of & to be converted into the HTML entity equivalent instead, so that the output becomes this?

<div id="box">
    <a href="http://domain.com/index.html&amp;location=1">First URL</a> 
    <a href="http://domain.com/index.html&amp;location=2">Second URL</a>
</div>

Solution

  • $('#box a').each(function(){
      $(this).attr('href', $(this).attr('href').replace('&','&amp;'));
      });