Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript passing an encoded url to window.location.href

Tags:

javascript

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

like image 556
user1213679 Avatar asked Feb 21 '14 14:02

user1213679


1 Answers

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. ;)

like image 148
taddy hoops Avatar answered Sep 21 '22 14:09

taddy hoops