All I want to do is encode the following link properly, but for some reason "#" is giving me a problem:
var text = "hello, how are you? &am fine"
var link = "http://example.com/test#zzzzzzzzz"
url = "http://twitter.com/share?url=" + link + "&text" + text;
$("#twitter a").attr("href", url)
I tried encodeURI
or encodeURIComponent
, but still have issue with "#". If I manually replace "#" with "%23", then for some reason the code is encoded again. Does the jQuery attr()
preform any encoding at all?
EDIT Trying escape produces
http://twitter.com/share?url=http%253A//example.com/test%2523zzzzzzzz
Not sure where the "%25" is coming from rather than just %23
Using encodeURIComponent
generates the following after doing $("#twitter a").attr("href", url)
. Where is the %25 is coming from?
http://twitter.com/share?url=http%253A%252F%252Fexample.com%252Ftest%2523zzzzzzzz
encodeURIComponent is not "complete", you can use a custom function like this (taken from http://phpjs.org/functions/urlencode/ ) :
function encode(toEncode) {
return encodeURIComponent(toEncode)
.replace(/!/g, '%21')
.replace(/'/g, '%27')
.replace(/\(/g, '%28')
.replace(/\)/g, '%29')
.replace(/\*/g, '%2A');
}
Example : var url = encode(url_plain_text);
encodeURIComponent
should work for you:
var text = "hello, how are you? & fine";
var link = "http://example.com/test#zzzzzzzzz";
var url = "http://twitter.com/share?url=" + encodeURIComponent(link) + "&text=" + encodeURIComponent(text);
$('#twitter a').attr('href', url);
jsFiddle example
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With