Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript encodeURIComponent With Backslash

w3schools says the following about encodeURIComponent function:

This function encodes special characters. In addition, it encodes the following characters: , / ? : @ & = + $ #.

Does that mean that it cannot encode a backslash (\)?

like image 885
Kevin Meredith Avatar asked Nov 26 '12 15:11

Kevin Meredith


People also ask

How do I use encodeURIComponent in Javascript?

The encodeURIComponent() function encodes a URI by replacing each instance of certain characters by one, two, three, or four escape sequences representing the UTF-8 encoding of the character (will only be four escape sequences for characters composed of two "surrogate" characters).

Should I use encodeURI or encodeURIComponent?

encodeURIComponent should be used to encode a URI Component - a string that is supposed to be part of a URL. encodeURI should be used to encode a URI or an existing URL.

What is the difference between encodeURI and encodeURIComponent?

The difference between encodeURI and encodeURIComponent is encodeURIComponent encodes the entire string, where encodeURI ignores protocol prefix ('http://') and domain name. encodeURIComponent is designed to encode everything, where encodeURI ignores a URL's domain related roots.

What can I use instead of escape in Javascript?

The escape() function is deprecated. Use encodeURI() or encodeURIComponent() instead.


1 Answers

This function encodes special characters. In addition, it encodes the following characters: , / ? : @ & = + $ # .

This definition is vague as to what "special characters" are. It sounds like a comparison between encodeURI and encodeURIComponent. Both will correctly escape \ as %5C, so you don't have to worry about backslashes.

encodeURI will leave the listed characters as it is assumed that the entire URI is being encoded:

encodeURI('http://example.com/foo bar/baz.html');
//produces "http://example.com/foo%20bar/baz.html"

encodeURIComponent will escape everything as it is assumed that the string is to be used as part of a query-string:

'http://example.com?foo=' + encodeURIComponent('http://example.com/fizz/buzz.html');
//produces "http://example.com?foo=http%3A%2F%2Fexample.com%2Ffizz%2Fbuzz.html"
like image 188
zzzzBov Avatar answered Oct 21 '22 19:10

zzzzBov