Can't set href with .attr ()

Change: . It was only a Firefox issue related to the Adblock Plus addon. Reinstalling the addon put an end to this strange behavior where URLs with some special characters would make anchors disappear altogether.

How to bind urls with special characters to href using jQuery?

I am currently doing the following:

var x = encodeURI(myURLhere)

      

I know it generates valid links because I used console.log(x)

to test it.

But when I do this:

$("#tweet").attr("href", x);

      

My anchor just disappears.

One example url where this happens:

https://twitter.com/intent/tweet?text=%22If%20it%20is%20not%20right%20do%20not%20do%20it;%20if%20it%20is%20not%20true%20do%20not%20say%20it.%22%20%E2%80%93%20Marcus%20Aurelius

      

Does anyone have any suggestions as to what I can do to assign such a url to my href anchor?

+3


source to share


1 answer


The problem is with the character ;

in the string not being encoded when used encodeURI

, instead you need to split the shutdown and just call encodeURIComponent()

on that.

Note. For this snippet to work, you will need to open the "Tweet" link in a new tab as Twitter cannot be shown in an iframe.



var text = 'If it is not right do not do it; if it is not true do not say it." โ€“ Marcus Aurelius"'
var x = encodeURIComponent(text);
$("#tweet").attr("href", 'https://twitter.com/intent/tweet?text=' + x);
      

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href="" id="tweet">Tweet</a>
      

Run codeHide result


+6


source







All Articles