Javascript window.open url with spaces and%

I am trying window.open with a URL with spaces:

 var msg = 'Hello, world!'; var url = 'http://yoursite.com'; var link = 'http://www.twitter.com/share?text=' + msg + '&url=' + url; window.open(link); 

Running this code will open a new window using http://twitter.com/share?text=Hello,%2520world!&url=http://yoursite.com .

What happens is that the space in msg is converted to% 20, then "%" is converted to% 25. As a workaround, I added:

msg = msg.replace(/\s/g, '+');

But are there any other characters that I need to track, or is there a better way around this?

+7
source share
3 answers

Try this instead:

 var msg = encodeURIComponent('Hello, world!'); var url = encodeURIComponent('http://www.google.com'); var link = 'http://twitter.com/intent/tweet?text=' + msg + '&url=' + url; window.open(link); 

Note the other Twitter URL and the query string parameter encoding.

+10
source

you need to encode the urls.

There should be no spaces in the URL.

Therefore, the browser will re-interpret the URL spaces at its discretion, unless you say exactly how:

 var msg = 'Hello,%20world!'; 
0
source

I had the same problem. It seems that if you use the url http://www.twitter.com , your msg will be double-escaped. If you look at the twitters dev page , they use https://twitter.com .

Remove www for your code and I find it useful to use https instead of http

 var msg = 'Hello, world!'; var url = 'http://yoursite.com'; var link = 'https://twitter.com/share?text=' + msg + '&url=' + url; window.open(link); 

You do not even need to use encodeURI or escape in your message.

0
source

All Articles