How to encode a URL with JavaScript
By Flavio
Tagged: JavaScript
Learn how to encode a URL in JavaScript and when to use encodeURI() for a full URL versus encodeURIComponent() for a single query parameter value.
How do you encode a URL in JavaScript?
Depending on what you need to do, there are 2 JavaScript functions that will help you.
The first is encodeURI(), and the second is encodeURIComponent().
Note: you might read about
escape(), but that is deprecated and should not be used.
Those 2 methods differ in which characters they do encode.
In details, encodeURI() does not encode ~!@#$&*()=:/,;?+ and encodeURIComponent() does not encode -_.!~*'(), encoding all the other characters. Why do they differ? Because they are meant for different uses:
encodeURI()is meant to encode a full URLencodeURIComponent()is meant to encode a single URL parameter value
If you were to call encodeURIComponent() on a full URL, since it does encode /, the URL path separators would be encoded as well (among other things):
encodeURI("https://flaviocopes.com/ hey!/")
//"https://flaviocopes.com/%20hey!/"
encodeURIComponent("https://flaviocopes.com/ hey!/")
// "https%3A%2F%2Fflaviocopes.com%2F%20hey!%2F"
MDN proposes an improvement to adhere to the RFC 3986 standard (http://tools.ietf.org/html/rfc3986), by implementing the following function:
const fixedEncodeURIComponent = (str) => {
return encodeURIComponent(str).replace(/[!'()*]/g, (c) => {
return '%' + c.charCodeAt(0).toString(16)
})
}
You call it for every single parameter that you’ll add to the URL.
If you are building a query string, you often don’t need these at all. The URL and URLSearchParams APIs encode values for you:
const params = new URLSearchParams()
params.set('q', 'go programming')
params.set('page', '1')
const url = `https://flaviocopes.com/search?${params}`
//https://flaviocopes.com/search?q=go+programming&page=1
URLSearchParams encodes each value, so you don’t call encodeURIComponent() by hand.
Be careful with encoding twice. encodeURIComponent('go programming') turns the space into %20. Encode that result again and you get %2520. The server then reads a literal %20, not a space.
Encode each parameter value once, then join the URL. Or let URLSearchParams do it.
The encodeURI() and encodeURIComponent() methods have a corresponding decodeURI() and decodeURIComponent() which does the opposite job which you can use on the backend if you use Node.js.
If you just need to encode or decode a string quickly, I built a free encode/decode tool that handles URL encoding, Base64 and HTML entities.
Want me to talk about your product? You can sponsor this site.
Related posts about js: