9

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

5
  • it's working fine at my side. Commented Feb 21, 2014 at 14:43
  • For me it's fine with chrome but not with firefox. Commented Feb 21, 2014 at 14:43
  • For me its working in both browsers. Commented Feb 21, 2014 at 14:49
  • 1
    Actually it's working on both. But firefox shows the unencoded url in the url bar. Commented Feb 21, 2014 at 14:50
  • Sounds like a versions issue! For interest's sake could you tell us what versions of what browser did not work for you? Commented Apr 11, 2014 at 8:36

1 Answer 1

6

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.