Languages
[Edit]
EN

TypeScript - encode / escape URL characters

3 points
Created by:
Mariam-Barron
781

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

Quick solution:

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

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

or:

const message: string = 'Hi! This is some message...';
const url: string = `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 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.

Practical examples:

// 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 alse

  1. JavaScript - encode / escape URL characters 
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