Reputation: 194
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&location=1">First URL</a>
<a href="http://domain.com/index.html&location=2">Second URL</a>
</div>
Upvotes: 1
Views: 4043
Reputation: 15576
$('#box a').each(function(){
$(this).attr('href', $(this).attr('href').replace('&','&'));
});
Upvotes: 3
Reputation: 4885
This will loop through all the
a
tags that exist in the document and will replace all the special chars in thehref
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();
}
Looping through all the
a
tags and replacing only the & symbol:
$('a').each(function(){
$(this).attr('href',$(this).attr('href').replace('&','&');
console.log($(this).attr('href'));
});
Upvotes: 2