Miker
Miker

Reputation: 194

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>

Upvotes: 1

Views: 4043

Answers (2)

sabithpocker
sabithpocker

Reputation: 15576

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

Upvotes: 3

silentw
silentw

Reputation: 4885

This will loop through all the a tags that exist in the document and will replace all the special chars in the href attribute into html entities

$('a').each(function(){
    $(this).attr('href',htmlEncode($(this).attr('href')));
    console.log($(this).attr('href'));
});


function htmlEncode(value){
  return $('<div/>').text(value).html();
}

Working demo


Looping through all the a tags and replacing only the & symbol:

$('a').each(function(){
    $(this).attr('href',$(this).attr('href').replace('&','&amp;');
    console.log($(this).attr('href'));
});

Upvotes: 2

Related Questions