Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to encode the following URL using Javascript or jQuery properly?

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
like image 355
Mark K Avatar asked Nov 17 '10 05:11

Mark K


2 Answers

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);

like image 129
Xartok Avatar answered Oct 08 '22 01:10

Xartok


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

like image 20
Jacob Relkin Avatar answered Oct 08 '22 01:10

Jacob Relkin