Encode URL in JavaScript

Last Updated On Friday 12th Nov 2021

javascript url encode

  • encodeuricomponent

encodeURIComponent()

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.

url encoding in javascript

Syntax

	encodeURIComponent(uriComponent);
	

Parameters

  • uriComponent – A string, number, boolean, null, undefined, or any object. Before encoding, the uriComponent gets converted to string.

javascript urlencode

encodeURI()

The encodeURI() 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.

Syntax

	encodeURI(URI)
	

js urlencode

Parameters

	URI - A complete URI.
	

The encodeURI() function does not encode characters that have special meaning (reserved characters) for a URI.

javascript encoding url

  • encodeURI() will not encode: ~!@#$&*()=:/,;?+'
  • encodeURIComponent() will not encode: ~!*()'
  • The characters A-Z a-z 0-9 - _ . ! ~ * ' ( ) are not escaped.

encodeuri

js url encode

Examples

	const url = 'https://codejagd.com'

console.log(encodeURI(url))             //https://codejagd.com
console.log(encodeURIComponent(url))    //https%3A%2F%2Fcodejagd.com

const paramComponent = '?q=search'
console.log(encodeURIComponent(paramComponent)) //"%3Fq%3Dsearch"
console.log(url + encodeURIComponent(paramComponent)) //https://codejagd.com%3Fq%3Dsearch
	

urlencode javascript

If you have

  • A complete URL, use encodeURI.
  • If You have a part of a URL, use encodeURIComponent.

References