All I want to do is encode the following link properly, but for some reason "#" is giving me a problem:
var text = "hello,开发者_StackOverflow社区 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
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
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);
According to Firebug:
>>> encodeURIComponent("http://example.com/test#zzzzzzzzz")
"http%3A%2F%2Fexample.com%2Ftest%23zzzzzzzzz"
What issues are you having with the '#'?
encodeURIComponent works fine for me. we can give the url like this in ajax call.The code shown below :
$.ajax({
cache: false,
type: "POST",
url: "http://atandra.mivamerchantdev.com//mm5/json.mvc?Store_Code=ATA&Function=Module&Module_Code=thub_connector&Module_Function=THUB_Request",
data: "strChannelName=" + $('#txtupdstorename').val() + "&ServiceUrl=" + encodeURIComponent($('#txtupdserviceurl').val()),
dataType: "HTML",
success: function (data) {
},
error: function (xhr, ajaxOptions, thrownError) {
}
});
精彩评论