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
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. ;)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With