Encode or decode URL query parameters, paths, and components using percent-encoding.
encodeURIComponent is the right tool for most values you put in a URL –
this lets you check your work before you ship a link or a redirect.
Why URL encoding matters. URLs can only safely contain a small set of
characters. Spaces, emoji, accented letters, &, ?,
and # all break a URL if left raw – a space in a query parameter
truncates the value, and # starts the fragment. Percent-encoding replaces
each unsafe character with a % followed by its two hexadecimal bytes. For
example, a space becomes %20, and an ampersand-powered value becomes
%26 so it isn't mistaken for a parameter separator.
encodeURIComponent vs encodeURI. In JavaScript,
encodeURIComponent is the right choice for a value you insert into a query
string or path segment because it escapes everything except the unreserved characters
(A–Z a–z 0–9 - _ . ! ~ * ' ( )). The broader encodeURI
leaves structural characters like ?, &, and #
intact, which is useful for encoding a whole URL but wrong for a single parameter. When
building query strings, encode each key and value separately and join them with
&.