Javascript passing an encoded url to window.location.href

javascript

Solution

This could be related to (a) using firefox or (b) specific APIs that you're feeding `encodedComponent` into, like Google search.

Here's one tested solution on Firefox-stable:

var clearComponent = 'flowers for my boyfriend & husband on valentines';
var encodedComponent = encodeURIComponent(clearComponent);
var googleSafeComponent = encodedComponent.replace(/%20/g,'+');  // replaces spaces with plus signs for Google and similar APIs
var completeURI = 'http://google.com/?q=' + googleSafeComponent;
window.location = completeURI;

Or all in one line:

window.location = 'http://google.com/?q=' + encodeURIComponent('flowers for my boyfriend & husband on valentines').replace(/%20/g,'+');

`window.location` implies `window.location.href` so you can save some letters. ;)

Problem

I'd like to redirect a page with javascript using the following code: ``` var s = 'http://blahblah/' + encodeURIComponent(something); alert(s); window.location.href = s; ``` The alert shows the correct encoded url but when I pass it to window.locaion.href, it redirects the page to the unencoded url which is wrong. How could I do it properly? Thanks

Original source