I'm trying window.open
with a url with spaces:
var msg = 'Hello, world!';
var url = '';
var link = '=' + msg + '&url=' + url;
window.open(link);
Running this code will open a new window with ,%2520world!&url=
.
What happens is that the space in msg is converted to %20, then the '%' is converted to %25. As a workaround, i added:
msg = msg.replace(/\s/g, '+');
But are there other chars i need to watch out for or is there a better workaround?
I'm 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 with http://twitter.com/share?text=Hello,%2520world!&url=http://yoursite.com
.
What happens is that the space in msg is converted to %20, then the '%' is converted to %25. As a workaround, i added:
msg = msg.replace(/\s/g, '+');
But are there other chars i need to watch out for or is there a better workaround?
Share Improve this question edited Apr 28, 2011 at 13:50 SLaks 887k181 gold badges1.9k silver badges2k bronze badges asked Mar 15, 2011 at 22:00 nymonymo 5421 gold badge5 silver badges15 bronze badges 1- i forgot to add that i'm using Drupal with jQuery. This code is wrapped within a Drupal.behaviors...not that i think these affect anything. – nymo Commented Mar 15, 2011 at 22:04
3 Answers
Reset to default 15Try 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 different Twitter url and the encoding of the query string params.
you have to encode URLs.
There cannot be any spaces in the URL.
Therefore the browser reinterprets the url spaces as it wants unless you tell it exactly how:
var msg = 'Hello,%20world!';
I had the same problem. It seems that if you use the url http://www.twitter.com
your msg gets escaped twice. If you look at twitters dev page, they use https://twitter.com
.
For your code, remove the www and I think it's good 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 don't even need to use encodeURI or escape on your message.