Reputation: 5674
Edit: It was a Firefox-only problem related to the addon Adblock Plus. Reinstalling the addon put an end to this weird behavior on which URLs with some specific special characters would make anchors disappear altogether.
How do I attribute URLs with specials characters to a href using jQuery?
What I'm doing right now is:
var x = encodeURI(myURLhere)
Which I know generates valid links, because I've been using console.log(x)
to check it.
But when I do:
$("#tweet").attr("href", x);
My anchor simply disappears.
One example of an URL on which that 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 suggestion as of what I can do to attribute such URL to my anchor's href?
Upvotes: 3
Views: 165
Reputation: 337560
The issue is because of the ;
character in the string, which is not encoded when using encodeURI
, instead you need to split the querystring off and just call encodeURIComponent()
on that directly.
Note: For this snippet to work you will need to open the 'Tweet' link in a new tab, as Twitter cannot be shown within the 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>
Upvotes: 6