Search code examples
javascripturlurlencodeurl-encoding

JS url encoding


when trying to encode the URL

http://www.example.com/events/tours/example-tour/?utm_source=example&utm_medium=banner

it gives me back the following:

http%3A%2F%2Fwww.example.com%2Fevents%2Ftours%2Fexample-tour%2F%3Futm_source%3Dexample%26utm_medium%3Dbanner%20

which does not represent a valid url, since it can not be called in browsers and leads to a google search (Chrome, you know?)

How can I encode the URL probably using JS only?


Solution

  • the right way in javascript to encode a url properly is

    encodeURIComponent();
    

    which gives you

    http%3A%2F%2Fwww.example.com%2Fevents%2Ftours%2Fexample-tour%2F%3Futm_source%3Dexample%26utm_medium%3Dbanner
    

    then

    decodeURIComponent();
    

    at the other side to decode the url again to make it valid.

    encodeURIComponent is not a valid url because you encodeit to pass is as a GET variable.

    like

    http://www.site.com/index.php?url=http%3A%2F%2Fwww.example.com%2Fevents%2Ftours%2Fexample-tour%2F%3Futm_source%3Dexample%26utm_medium%3Dbanner