When are you supposed to use escape instead of encodeURI / encodeURIComponent?

Linux web server topics
Post Reply
admin
Site Admin
Posts: 50
Joined: Sun Aug 08, 2021 7:49 am

When are you supposed to use escape instead of encodeURI / encodeURIComponent?

Post by admin »

When encoding a query string to be sent to a web server - when do you use escape() and when do you use encodeURI() or encodeURIComponent():

Use escape:

escape("% +&=");
OR

use encodeURI() / encodeURIComponent()

encodeURI("http://www.google.com?var1=value1&var2=value2");

encodeURIComponent("var1=value1&var2=value2");
It's worth pointing out that encodeURIComponent("var1=value1&var2=value2") is not the typical use case. That example will encode the = and &, which is probably not what was intended! encodeURIComponent is typically applied separately to just the value in each key value pair (the part after each =). –
Timothy Shields
Mar 14, 2014 at 20:45
3
do you need to do anything to the key? What if it has an = in it? (is that even possible?) –
Mala
Jun 9, 2014 at 21:49
3
@Mala I'm still new to web programming in general, but what I've used in my limited experience is to encode the key and the value separately, ensuring the '=' stays: var params = encodeURIComponent(key) + '=' + encodeURIComponent(value); - Maybe someone else knows a better way. –
Ned
Jun 28, 2014 at 21:17
1
@nedshares I was playing with that, but as far as I can tell the key doesn't seem to be encoded... at least not in the same way. Maybe it's against spec to have an = in the key? –
Mala
Jul 1, 2014 at 20:08
2
Also worth pointing out that recent JavaScript implementations provide the higher-level interfaces URL and URLSearchParams for manipulating URLs and their query strings. –
Post Reply