0

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?

1 Answer 1

1

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
Sign up to request clarification or add additional context in comments.

5 Comments

since only Chars like '&' and '=' need to get encoded would you recommend to do a simple replace?
i always go with encodeURIComponent if i pass the url as a GET variable, but i don't know exactly what you wanna achieve.
I am localizing some banners, based on XML and when extracting the URI and encoding it, the URI is broken. Applied the replace fix and works like a charm for me.
so you need to decode the url decodeURIComponent()? there is also decodeURI()..but if the replace works... keep that ..
appreciate your support! :)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.