Languages
[Edit]
EN

JavaScript - encode / escape URL characters

25 points
Created by:
Root-ssh
175460

In this short article, we would like to show how in JavaScript, use encodeURIComponent() function to escape all unsafe characters in some URL.

Quick solution:

// ONLINE-RUNNER:browser;

const url = `/?message=${encodeURIComponent('How are you?')}`;

console.log(url);  // /?message=How%20are%20you%3F

or:

// ONLINE-RUNNER:browser;

const message = 'Hi! This is some message...';
const url = `https://my-domain.com/chat?message=${encodeURIComponent(message)}`;

console.log(url);  // https://my-domain.com/chat?message=Hi!%20This%20is%20some%20message...

 

Explaination

encodeURIComponent() function converts/escapes characters in the following way:

Not escaped characters

Digits, small and big English letters:
0-9 a-z A-Z

Some special characters:
~ ! * - _ . ' ( )
Escaped characters

Non-English alphabets.
e.g. 日本 Россия ąćęłńóśźż etc.

Reserved symbols in URL / URI:
@ : / ? # & =

Unicode characters like emoji, icons, symbols, etc.
e.g. 🚀 🍏 🍌 ❤️ 💻 🙂

  \t \n - spaces, tabulators, newlines, etc.
Characters that are not counted in the Not escaped characters column.

Runnable examples:

// ONLINE-RUNNER:browser;

// Not escaped characters:

console.log(encodeURIComponent(`0123456789`));                  // 0123456789
console.log(encodeURIComponent(`abcdefghijklmnopqrstuvwxyz`));  // abcdefghijklmnopqrstuvwxyz
console.log(encodeURIComponent(`ABCDEFGHIJKLMNOPQRSTUVWXYZ`));  // ABCDEFGHIJKLMNOPQRSTUVWXYZ
console.log(encodeURIComponent(`~!*-_.'()`));                   // ~!*-_.'()

// Some escaped characters:

console.log(encodeURIComponent(`日本`));             // %E6%97%A5%E6%9C%AC
console.log(encodeURIComponent(`Россия`));           // %D0%A0%D0%BE%D1%81%D1%81%D0%B8%D1%8F
console.log(encodeURIComponent(`ąćęłńóśźż`));        // %C4%85%C4%87%C4%99%C5%82%C5%84%C3%B3%C5%9B%C5%BA%C5%BC
console.log(encodeURIComponent(`@:/?#&=`));          // %40%3A%2F%3F%23%26%3D
console.log(encodeURIComponent(`🚀🍏🍌❤️💻🙂`));  // %F0%9F%9A%80%F0%9F%8D%8F%F0%9F%8D%8C%E2%9D%A4%EF%B8%8F%F0%9F%92%BB%F0%9F%99%82
console.log(encodeURIComponent(` \t\n`));            // %20%09%0A

 

See also

  1. JavaScript - decode url characters

  2. JavaScript - base64 with Unicode support

  3. TypeScript - encode / escape URL characters

Alternative titles

  1. JavaScript - encodeURIComponent() function example
  2. JavaScript - encode / escape URL request parameter values
  3. JavaScript - encode URI component function example
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join