Languages
[Edit]
EN

JavaScript - encode / escape URL characters

25 points
Created by:
Root-ssh
115270

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...

 

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

Not escaped charactersEscaped characters
0-9 - digits

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

a-z A-Z - small and big English letters

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

~ ! * - _ . ' ( ) - some special characters

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

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