Skip to content

How to encode a URL with JavaScript

You need to encode a URL using JavaScript such that it can be put into a GET string.

How do you encode a URL and send a GET request in JavaScript?

There are three JavaScript functions that will help you.

  • escape()
  • encodeURI()
  • encodeURIComponent()

escape()

The escape() function computes a new string from an existing string in which certain characters have been replaced by a hexadecimal escape sequence. escape() is removed from the web standards but it’s not strictly deprecated.

escape('poop code'); // "poop%20code"
escape('ć');         // "%u0107"

This function was used mostly for URL queries (the part of a URL following ‘?’) not for escapes in ordinary String literals, which use the format “\xHH”, where HH are two hexadecimal digits (with \xHH\xHH… for higher-plane Unicode characters). Escaped characters in String literals can be expanded by replacing the \x by % and then using the decodeURIComponent function.

encodeURI()

encodeURI() returns a new string representing the provided string encoded as a URI. It’s primarily meant to encode a full URL It escapes all characters except A-Z a-z 0-9 ; , / ? : @ & = + $ – _ . ! ~ * ‘ ( ) #

encodeURI('poop code'); // "poop%20code"
encodeURI('-_.!~*'()');         // "-_.!~*'()"

encodeURIComponent()

encodeURIComponent() returns a new string representing the provided string encoded as a URI component. It’s primarily meant to encode a single URL parameter value. It escapes all characters except A-Z a-z 0-9 - _ . ! ~ * ' ( )

encodeURIComponent('poop code'); // "poop%20code"
encodeURIComponent('-_.!~*'()');         // "-_.!~*'()"
encodeURIComponent('#') 			// "%23"

encodeURI() and encodeURIComponent() encode different sets of characters, and select the one you need appropriately. encodeURI() encodes fewer characters than encodeURIComponent(), which encodes fewer characters than escape().

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.