How to do URL Encoding in Javascript

You can encode URI components like query strings or path segments in Javascript using the encodeURIComponent() function. It uses the UTF-8 encoding scheme to encode URI components.

URL encoding, sometimes also referred to as percent encoding, is a mechanism for encoding any data in URLs to a safe and secure format that can be transmitted over the internet. URL encoding is also used to prepare data for submitting HTML forms with application/x-www-form-urlencoded MIME type.

Javascript URL encoding using the encodeURIComponent() function

The following example demonstrates how to encode URI components in Javascript -

var value = 'Hellö Wörld@Javascript'
var encodedValue = encodeURIComponent(value)

// Hell%C3%B6%20W%C3%B6rld%40Javascript

Note that, you should not encode the entire URL using the encodeURIComponent() function. It should only be used to encode the query strings or path segments -

var baseUrl = ''
var query = 'Hellö Wörld@Javascript'

// encode only the query string
var completeUrl = baseUrl + encodeURIComponent(query)


Also Read: How to Decode URI components in Javascript