Menu

1 / 2

Building a URL Encoder/Decoder — encodeURIComponent vs encodeURI, When to Use Each, and Component-Level Encoding

DEV Community·Shaishav Patel·6 months ago
#cDZ4Utjg
#javascript#webdev#tutorial#string#value
Reading 0:00
15s threshold

The URL Encoder/Decoder at Ultimate Tools encodes and decodes URL strings. The non-obvious part isn't the encoding itself — it's choosing between encodeURIComponent , encodeURI , and a custom component-level encoder, and knowing when each one is correct.

The Two Built-in Functions

JavaScript ships with two percent-encoding functions:

encodeURI ( ' https://example.com/path?q=hello world&lang=en ' ) // → 'https://example.com/path?q=hello%20world&lang=en'

encodeURIComponent ( ' https://example.com/path?q=hello world&lang=en ' ) // → 'https%3A%2F%2Fexample.com%2Fpath%3Fq%3Dhello%20world%26lang%3Den'

Enter fullscreen mode

Exit fullscreen mode

The difference:

encodeURI encodes characters that are invalid in a complete URL but leaves URL structure characters alone ( / ? # : @ & = + $ ). Use when encoding a whole URL.

encodeURIComponent encodes everything except letters, digits, and - _ . ! ~ * ' ( ) .…

Continue reading — create a free account

Join HashtagPLUS to read full articles, follow hashtags, vote, and join the conversation.