Javascript window.open url with spaces and %

nymo picture nymo · Mar 15, 2011 · Viewed 21.3k times · Source

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?

Answer

DTRx picture DTRx · Jul 20, 2011

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 different Twitter url and the encoding of the query string params.