{"id":915,"date":"2024-02-20T08:13:21","date_gmt":"2024-02-20T14:13:21","guid":{"rendered":"https:\/\/frontendmasters.com\/blog\/?p=915"},"modified":"2024-02-20T08:13:21","modified_gmt":"2024-02-20T14:13:21","slug":"encoding-and-decoding-urls-in-javascript","status":"publish","type":"post","link":"https:\/\/frontendmasters.com\/blog\/encoding-and-decoding-urls-in-javascript\/","title":{"rendered":"Encoding and Decoding URLs in JavaScript"},"content":{"rendered":"\n<p>URL, which stands for <strong>U<\/strong>niform <strong>R<\/strong>esource <strong>L<\/strong>ocator, is an address to access resources on the internet. Each URL points to a unique resource on the web. URLs can sometimes contain special characters or need to be manipulated dynamically.<\/p>\n\n\n\n<p>In this article, we\u2019ll explore the modern techniques for working with URLs in JavaScript, and answer the <strong>how<\/strong>, <strong>why<\/strong> and <strong>when<\/strong> questions relating to encoding and decoding URLs in JavaScript.<\/p>\n\n\n\n<p>When you type something into a browser, a search result or various search results are provided. These search results come in a confusing format with text and special characters such as %, +,?, =, &amp;, &lt;, &gt;, and so on.<\/p>\n\n\n\n<p>Look at this result from the Frontend Masters &#8216;courses&#8217; section on the blog page.<\/p>\n\n\n\n<figure class=\"wp-block-image size-large\"><img data-recalc-dims=\"1\" loading=\"lazy\" decoding=\"async\" width=\"1024\" height=\"99\" src=\"https:\/\/i0.wp.com\/frontendmasters.com\/blog\/wp-content\/uploads\/2024\/02\/s_700D6D6369EC00B83D6370B9E7B96F2C4C2EED3CE9C1D47FD83F2547E8299331_1708009694206_urlspecialcharacter-frontendmasters.png?resize=1024%2C99&#038;ssl=1\" alt=\"\" class=\"wp-image-918\" srcset=\"https:\/\/i0.wp.com\/frontendmasters.com\/blog\/wp-content\/uploads\/2024\/02\/s_700D6D6369EC00B83D6370B9E7B96F2C4C2EED3CE9C1D47FD83F2547E8299331_1708009694206_urlspecialcharacter-frontendmasters.png?resize=1024%2C99&amp;ssl=1 1024w, https:\/\/i0.wp.com\/frontendmasters.com\/blog\/wp-content\/uploads\/2024\/02\/s_700D6D6369EC00B83D6370B9E7B96F2C4C2EED3CE9C1D47FD83F2547E8299331_1708009694206_urlspecialcharacter-frontendmasters.png?resize=300%2C29&amp;ssl=1 300w, https:\/\/i0.wp.com\/frontendmasters.com\/blog\/wp-content\/uploads\/2024\/02\/s_700D6D6369EC00B83D6370B9E7B96F2C4C2EED3CE9C1D47FD83F2547E8299331_1708009694206_urlspecialcharacter-frontendmasters.png?resize=768%2C74&amp;ssl=1 768w, https:\/\/i0.wp.com\/frontendmasters.com\/blog\/wp-content\/uploads\/2024\/02\/s_700D6D6369EC00B83D6370B9E7B96F2C4C2EED3CE9C1D47FD83F2547E8299331_1708009694206_urlspecialcharacter-frontendmasters.png?w=1439&amp;ssl=1 1439w\" sizes=\"auto, (max-width: 1000px) 100vw, 1000px\" \/><\/figure>\n\n\n\n<p>See the special characters in the URL on the search bar? They&#8217;re referred to as encoded characters.<\/p>\n\n\n\n<p>As a way to familiarize yourself and see how common they are, try searching something in your browser to see the results and identify the encoded characters. For example, try searching &#8216;What are URLs?&#8217;.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Working with URLs in JavaScript<\/h2>\n\n\n\n<p>Before getting into encoding and decoding URLs, we need to learn how to work with URLs in JavaScript. This is useful for when you need to construct, parse, and manipulate web addresses. Modern JavaScript provides a built-in <code>URL<\/code> class, which offers powerful features for working with URLs:<\/p>\n\n\n\n<ol class=\"wp-block-list\">\n<li><strong>Creating a URL object:<\/strong> To work with URLs in JavaScript, you can create a URL object using this URL syntax.<\/li>\n<\/ol>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-1\" data-shcb-language-name=\"JavaScript\" data-shcb-language-slug=\"javascript\"><span><code class=\"hljs language-javascript\"><span class=\"hljs-keyword\">const<\/span> url = <span class=\"hljs-keyword\">new<\/span> URL(<span class=\"hljs-string\">\"https:\/\/sample.com\/search?q=hello world\"<\/span>);<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-1\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">JavaScript<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">javascript<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<ol class=\"wp-block-list\" start=\"2\">\n<li><strong>Accessing URL components:<\/strong> You can access various components of the URL once you have a URL object. You can access components such as the: <ul> <li><code>url.protocol<\/code>: Returns the protocol of the URL (e.g &#8220;https:&#8221;)<\/li>   <li><code>url.hostname<\/code>: Returns the hostname of the URL (e.g &#8220;sample.com&#8221;)<\/li>   <li><code>url.pathname<\/code>: Returns the path of the URL (e.g &#8220;\/search&#8221;)<\/li>   <li><code>url.searchParams<\/code>: Returns a URLSearchParams object containing the query parameters<\/li><\/ul><\/li>\n<\/ol>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-2\" data-shcb-language-name=\"JavaScript\" data-shcb-language-slug=\"javascript\"><span><code class=\"hljs language-javascript\"><span class=\"hljs-built_in\">console<\/span>.log(url.protocol);     <span class=\"hljs-comment\">\/\/ Output: https:<\/span>\n<span class=\"hljs-built_in\">console<\/span>.log(url.hostname);     <span class=\"hljs-comment\">\/\/ Output: sample.com<\/span>\n<span class=\"hljs-built_in\">console<\/span>.log(url.pathname);     <span class=\"hljs-comment\">\/\/ Output: \/search<\/span>\n<span class=\"hljs-built_in\">console<\/span>.log(url.searchParams); <span class=\"hljs-comment\">\/\/ Output: q=hello+world<\/span><\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-2\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">JavaScript<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">javascript<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<ol class=\"wp-block-list\" start=\"3\">\n<li><strong>Converting URL object or component to string:<\/strong> You can use the <code>toString()<\/code> JavaScript method to obtain a URL or in this case, a URL component as a string. <\/li>\n<\/ol>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-3\" data-shcb-language-name=\"JavaScript\" data-shcb-language-slug=\"javascript\"><span><code class=\"hljs language-javascript\"><span class=\"hljs-built_in\">console<\/span>.log(url.searchParams.toString());\n<span class=\"hljs-comment\">\/\/ Output: q=hello+world<\/span><\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-3\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">JavaScript<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">javascript<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<ol class=\"wp-block-list\" start=\"4\">\n<li><strong>Getting the current page URL<\/strong>: To get the current URL of a web page you\u2019re currently on, use the <code>window.location.href<\/code> property.<\/li>\n<\/ol>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-4\" data-shcb-language-name=\"JavaScript\" data-shcb-language-slug=\"javascript\"><span><code class=\"hljs language-javascript\"><span class=\"hljs-keyword\">const<\/span> currentUrl = <span class=\"hljs-built_in\">window<\/span>.location.href;\n<span class=\"hljs-built_in\">console<\/span>.log(currentUrl);\n<span class=\"hljs-comment\">\/\/ Output: Logs out your current URL<\/span><\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-4\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">JavaScript<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">javascript<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<ol class=\"wp-block-list\" start=\"5\">\n<li><strong>Modifying URL components:<\/strong> You can easily modify query parameters of a URL using the <code>searchParams<\/code> property of the URL object.<\/li>\n<\/ol>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-5\" data-shcb-language-name=\"JavaScript\" data-shcb-language-slug=\"javascript\"><span><code class=\"hljs language-javascript\">url.searchParams.set(<span class=\"hljs-string\">\"q\"<\/span>, <span class=\"hljs-string\">\"new query\"<\/span>);\n<span class=\"hljs-built_in\">console<\/span>.log(url.searchParams.toString());\n<span class=\"hljs-comment\">\/\/ Output: q=new+query<\/span><\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-5\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">JavaScript<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">javascript<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>This will update the value of the &#8220;q&#8221; query parameter from \u201chello world\u201d to &#8220;new query&#8221; in an encoded format.<\/p>\n\n\n\n<ol class=\"wp-block-list\" start=\"6\">\n<li><strong>Constructing new URLs:<\/strong> You can also construct new URLs by combining different components or modifying existing ones.<\/li>\n<\/ol>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-6\" data-shcb-language-name=\"JavaScript\" data-shcb-language-slug=\"javascript\"><span><code class=\"hljs language-javascript\"><span class=\"hljs-keyword\">const<\/span> newURL = <span class=\"hljs-keyword\">new<\/span> URL(<span class=\"hljs-string\">\"https:\/\/sample.com\"<\/span>);\nnewURL.pathname = <span class=\"hljs-string\">\"\/new-path\"<\/span>;\nnewURL.searchParams.set(<span class=\"hljs-string\">\"q\"<\/span>, <span class=\"hljs-string\">\"new query\"<\/span>);\n<span class=\"hljs-built_in\">console<\/span>.log(newURL.toString())\n<span class=\"hljs-comment\">\/\/ Output: https:\/\/sample.com\/new-path?q=new+query<\/span><\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-6\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">JavaScript<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">javascript<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>The above lines of code constructs a new URL by first creating a URL object, setting the pathname, and setting the query parameter. It then converts the result to a string for easy reading.<\/p>\n\n\n\n<p>Try running all the code snippets provided above to get an idea of how to work with URLs in JavaScript.<\/p>\n\n\n\n<p>Now that we\u2019ve learned how to work with URLs in JavaScript, we\u2019ll learn how to encode and decode URLs in JavaScript as it is an important skill for web developers to acquire.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Encoding URLs in JavaScript<\/h2>\n\n\n\n<p>Encoding a URL essentially means converting special characters in a URL into a format that can be properly transmitted over the internet.<\/p>\n\n\n\n<p>This process is necessary because some characters in URLs, such as spaces or symbols, can have unique meanings, and encoding them ensures that browsers and web servers interpret them correctly.<\/p>\n\n\n\n<p>Now, why do URLs need to be encoded? This is because URLs are limited in the characters they can include by default. The standard URL specification states that URLs can only contain characters from the ASCII character set, which consists of 128 characters. These characters include uppercase and lowercase letters, numbers, and a limited collection of special characters, such as &#8220;-&#8220;, &#8220;_&#8221;, &#8220;.&#8221;, and &#8220;~&#8221;.<\/p>\n\n\n\n<p>Reserved characters, which have specific meanings in URLs, are not part of the standard ASCII set and must be encoded if used in a URL. The reserved characters are &#8220;\/&#8221;, &#8220;[&#8221; and &#8220;]&#8221;, &#8220;@&#8221;, &#8220;%&#8221;, &#8220;:&#8221;, &#8220;&amp;&#8221;, &#8220;#&#8221;, &#8220;@&#8221;, &#8220;=&#8221;,&#8221; and so on.<\/p>\n\n\n\n<p>To include reserved characters in a URL, they must be percent-encoded, which means replacing them with a percent sign (&#8220;%&#8221;) followed by their hexadecimal value. For example, because URLs cannot contain spaces, the space character (&#8221; &#8220;) is encoded as &#8220;%20&#8221; or &#8220;+&#8221;, and the ampersand (&#8220;&amp;&#8221;) is encoded as &#8220;%26&#8221;.<\/p>\n\n\n\n<p>JavaScript provides two functions for encoding URLs: <code>encodeURI()<\/code> and <code>encodeURIComponent()<\/code>.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">The <code>encodeURIComponent()<\/code> Function<\/h3>\n\n\n\n<p>The <code>encodeURIComponent()<\/code> function encodes a URI component, such as query parameters, in which some characters have special meaning and must be encoded. It encodes all characters except the standard ASCII alphanumeric characters (A-Z, a-z, and 0-9), hyphen (&#8220;-&#8220;), underscore (&#8220;_&#8221;), period (&#8220;.&#8221;), and tilde (&#8220;~&#8221;).<\/p>\n\n\n\n<p class=\"learn-more\">URI stands for Unique Resource Identifier. A URL <em>is<\/em> a URI. <a href=\"https:\/\/danielmiessler.com\/p\/difference-between-uri-url\/\">There is a difference<\/a> but it&#8217;s nothing to fret about.<\/p>\n\n\n\n<p>Take a look at the code snippets below and their results:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-7\" data-shcb-language-name=\"JavaScript\" data-shcb-language-slug=\"javascript\"><span><code class=\"hljs language-javascript\"><span class=\"hljs-keyword\">const<\/span> url = <span class=\"hljs-string\">\"https:\/\/frontendmasters.com\"<\/span>;\n<span class=\"hljs-keyword\">const<\/span> encodedURL = <span class=\"hljs-built_in\">encodeURIComponent<\/span>(url);\n<span class=\"hljs-built_in\">console<\/span>.log(encodedURL);\n<span class=\"hljs-comment\">\/\/ Output: https%3A%2F%2Ffrontendmasters.com<\/span><\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-7\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">JavaScript<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">javascript<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>In this first example, we defined a variable &#8216;url&#8217; and assigned it a value &#8211; \u2018https:frontendmasters.com\u2019 (the URL to encode). Next, we call the <code>encodedURIComponent()<\/code> function, passing the &#8216;url&#8217; as an argument. The function then encodes the URL by replacing specific characters with their percent-coded representation and logs it to the terminal.<\/p>\n\n\n\n<p>Characters like &#8216;:&#8217; and &#8216;\/&#8217; have been replaced with their percent-coded representations (%3A and %2F, respectively).<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-8\" data-shcb-language-name=\"JavaScript\" data-shcb-language-slug=\"javascript\"><span><code class=\"hljs language-javascript\"><span class=\"hljs-keyword\">const<\/span> url2 = <span class=\"hljs-string\">\"mango &amp;amp; pineapple\"<\/span>;\n<span class=\"hljs-keyword\">const<\/span> encodedURL2 = <span class=\"hljs-built_in\">encodeURIComponent<\/span>(url2);\n<span class=\"hljs-built_in\">console<\/span>.log(encodedURL2);\n<span class=\"hljs-comment\">\/\/ Output: mango%20%26%20pineapple <\/span><\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-8\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">JavaScript<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">javascript<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>In example 2, can you see the &#8220;%20&#8221; and &#8220;%26&#8221; symbols that represent the space and ampersand (&amp;) characters? The value passed isn&#8217;t a URL, but it&#8217;s a nice example of how JavaScript encodes spaces and ampersands.<\/p>\n\n\n\n<p>For additional information on the <code>encodeURIComponent()<\/code> function, see the <a href=\"https:\/\/developer.mozilla.org\/en-US\/docs\/Web\/JavaScript\/Reference\/Global_Objects\/encodeURIComponent\">MDN documentation<\/a>.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">The <code>encodeURI()<\/code> Function<\/h3>\n\n\n\n<p>The <code>encodeURI<\/code> function is used to encode an entire URI, including the entire URL. It does not encode certain characters that are allowed in a URI, such as letters, digits, hyphens, periods, and underscores.<\/p>\n\n\n\n<p>The characters that are not encoded by <code>encodeURI<\/code> are the same as those for the <code>encodeURIComponent<\/code> function, plus several more, namely:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Question mark (&#8220;?&#8221;)<\/li>\n\n\n\n<li>Hash sign (&#8220;#&#8221;)<\/li>\n\n\n\n<li>Dollar sign (&#8220;$&#8221;)<\/li>\n\n\n\n<li>Ampersand (&#8220;&amp;&#8221;)<\/li>\n\n\n\n<li>Comma (&#8220;,&#8221;)<\/li>\n\n\n\n<li>Forward slash (&#8220;\/&#8221;)<\/li>\n\n\n\n<li>Colon (&#8220;:&#8221;)<\/li>\n\n\n\n<li>Semi-colon (&#8220;;&#8221;)<\/li>\n\n\n\n<li>At sign (&#8220;@&#8221;)<\/li>\n\n\n\n<li>Equals sign (&#8220;=&#8221;)<\/li>\n\n\n\n<li>Plus sign (&#8220;+&#8221;)<\/li>\n<\/ul>\n\n\n\n<p>Let\u2019s look at some code snippets.<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-9\" data-shcb-language-name=\"JavaScript\" data-shcb-language-slug=\"javascript\"><span><code class=\"hljs language-javascript\"><span class=\"hljs-keyword\">const<\/span> url = <span class=\"hljs-string\">'https:\/\/www.twitter.com'<\/span>;\n<span class=\"hljs-built_in\">console<\/span>.log(<span class=\"hljs-built_in\">encodeURI<\/span>(url)); \n<span class=\"hljs-comment\">\/\/ Output: https:\/\/www.twitter.com<\/span><\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-9\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">JavaScript<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">javascript<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>The result remains the same as the URL given because the <code>encodeURI()<\/code> function does not encode some characters such as slash, period, and colon.<\/p>\n\n\n\n<p>If you use the <code>encodeURIComponent()<\/code> on the same example, you will observe that some characters are encoded. Let&#8217;s try it out.<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-10\" data-shcb-language-name=\"JavaScript\" data-shcb-language-slug=\"javascript\"><span><code class=\"hljs language-javascript\"><span class=\"hljs-keyword\">const<\/span> url = <span class=\"hljs-string\">'https:\/\/www.twitter.com'<\/span>;\n<span class=\"hljs-built_in\">console<\/span>.log(<span class=\"hljs-built_in\">encodeURIComponent<\/span>(url)); \n<span class=\"hljs-comment\">\/\/ Output: https%3A%2F%2Fwww.twitter.com<\/span><\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-10\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">JavaScript<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">javascript<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>Now, for a more complex code sample, the value of the URL to be encoded is a query parameter.<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-11\" data-shcb-language-name=\"JavaScript\" data-shcb-language-slug=\"javascript\"><span><code class=\"hljs language-javascript\"><span class=\"hljs-keyword\">const<\/span> url = <span class=\"hljs-string\">\"https:\/\/sample.com\/search?q=hello world\"<\/span>;\n\n<span class=\"hljs-built_in\">console<\/span>.log(<span class=\"hljs-built_in\">encodeURI<\/span>(url));\n<span class=\"hljs-comment\">\/\/ Output: \"https:\/\/sample.com\/search?q=hello%20world\"<\/span>\n\n<span class=\"hljs-built_in\">console<\/span>.log(<span class=\"hljs-built_in\">encodeURIComponent<\/span>(url));\n<span class=\"hljs-comment\">\/\/ Output: https%3A%2F%2Fsample.com%2Fsearch%3Fq%3Dhello%20world<\/span>\n<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-11\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">JavaScript<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">javascript<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>The <code>encodeURI()<\/code> function simply encodes the space character in the query input as &#8220;%20&#8221;. On the other hand, the <code>encodeURIComponent()<\/code> encodes the colon, the slash, and the space character in the query parameter.<\/p>\n\n\n\n<p>For additional information on the <code>encodeURI()<\/code> function, see the <a href=\"https:\/\/developer.mozilla.org\/en-US\/docs\/Web\/JavaScript\/Reference\/Global_Objects\/encodeURI\">MDN documentation<\/a>.<\/p>\n\n\n\n<p>The key to understanding the differences between these two functions is to note which characters are encoded and which are not encoded for both functions. While they are slightly different, they both perform the same action &#8211; encoding URLs to make them easier to transfer across the internet.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Reasons You\u2019d Need to Encode Your URLs<\/h3>\n\n\n\n<ol class=\"wp-block-list\">\n<li><strong>Safety and Accuracy:<\/strong> URLs may contain special characters, such as spaces or query parameters, which web servers or browsers may misinterpret. Encoding URLs ensures that special characters are correctly interpreted, reducing errors and ensuring accurate transmission.<\/li>\n\n\n\n<li><strong>Data Integrity:<\/strong> When sending data in URLs, such as search queries or form submissions, encoding ensures that the data is preserved during transmission. Decoding allows the data to be correctly processed and interpreted by the receiver.<\/li>\n<\/ol>\n\n\n\n<h2 class=\"wp-block-heading\">Decoding URLs in JavaScript<\/h2>\n\n\n\n<p>Decoding is the opposite of encoding. It reverts the effect of encoded URLs.<\/p>\n\n\n\n<p>Decoding a URL entails converting percent-coded characters back to their original form. Decoding is important when you receive an encoded URL and need to extract information from it, similar to solving a puzzle in which you must decode to receive the message.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">The <code>decodeURIComponent()<\/code> Function<\/h3>\n\n\n\n<p>In JavaScript, you can decode a URL using the <code>decodeURIComponent()<\/code> function. When calling this function to decode a URL, it decodes each component of the URI.<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-12\" data-shcb-language-name=\"JavaScript\" data-shcb-language-slug=\"javascript\"><span><code class=\"hljs language-javascript\"><span class=\"hljs-keyword\">const<\/span> encodedURL = <span class=\"hljs-string\">\"https%3A%2F%2Fsample.com%2Fsearch%3Fq%3Dhello%20world\"<\/span>;\n<span class=\"hljs-built_in\">console<\/span>.log(<span class=\"hljs-built_in\">decodeURIComponent<\/span>(encodedURL));\n<span class=\"hljs-comment\">\/\/ Output: \"https:\/\/sample.com\/search?q=hello world\"&amp;quot;\"<\/span>\n<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-12\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">JavaScript<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">javascript<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>Here, the <code>decodeURIComponent()<\/code> function takes the encoded URL as input and returns the decoded URL.<\/p>\n\n\n\n<p>This <a href=\"https:\/\/developer.mozilla.org\/en-US\/docs\/Web\/JavaScript\/Reference\/Global_Objects\/decodeURIComponent\">MDN documentation<\/a> offers more information on this function.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">The <code>decodeURI()<\/code> Function<\/h3>\n\n\n\n<p>The <code>decodeURI()<\/code> function is used to decode the entire URI including domain, path, and query parameters.<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-13\" data-shcb-language-name=\"JavaScript\" data-shcb-language-slug=\"javascript\"><span><code class=\"hljs language-javascript\"><span class=\"hljs-keyword\">const<\/span> url = <span class=\"hljs-string\">\"https:\/\/sample.com\/search?q=hello world\"<\/span>;\n<span class=\"hljs-built_in\">console<\/span>.log(<span class=\"hljs-built_in\">encodeURI<\/span>(url));\n<span class=\"hljs-comment\">\/\/ Output: https:\/\/sample.com\/search?q=hello%20world<\/span>\n\n<span class=\"hljs-built_in\">console<\/span>.log(<span class=\"hljs-built_in\">decodeURI<\/span>(url));\n<span class=\"hljs-comment\">\/\/ Output: https:\/\/sample.com\/search?q=hello world<\/span>\n<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-13\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">JavaScript<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">javascript<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>In the above example, we encode a URL query parameter using the <code>encodeURI()<\/code> function and decode the encoded URL using the <code>decodeURI()<\/code> function.<\/p>\n\n\n\n<p>Check out the <a href=\"https:\/\/developer.mozilla.org\/en-US\/docs\/Web\/JavaScript\/Reference\/Global_Objects\/decodeURI\">MDN documentation<\/a> for further information on the <code>decodeURI()<\/code> method.<\/p>\n\n\n\n<p>Learning how to encode and decode URLs in JavaScript is one thing; understanding <strong>when<\/strong> to encode and decode URLs is another.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">When to Encode a URL<\/h2>\n\n\n\n<p>Here are some common scenarios when you might need to encode a URL:<\/p>\n\n\n\n<ol class=\"wp-block-list\">\n<li><strong>Generating Dynamic URLs:<\/strong> If your application generates URLs dynamically, like when generating links based on user input or database values, ensure that any user-generated input is properly encoded. This ensures that any special characters in the URLs are converted into a format that can be safely transmitted over the internet.<\/li>\n<\/ol>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-14\" data-shcb-language-name=\"JavaScript\" data-shcb-language-slug=\"javascript\"><span><code class=\"hljs language-javascript\"><span class=\"hljs-keyword\">const<\/span> dynamicValue = <span class=\"hljs-string\">\"hello world\"<\/span>;\n<span class=\"hljs-keyword\">const<\/span> encodedURL = <span class=\"hljs-string\">\"https:\/\/example.com\/search?q=\"<\/span> + <span class=\"hljs-built_in\">encodeURIComponent<\/span>(dynamicValue);\n<span class=\"hljs-built_in\">console<\/span>.log(encodedURL);\n<span class=\"hljs-comment\">\/\/ Output: \"https:\/\/example.com\/search?q=hello%20world\"<\/span><\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-14\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">JavaScript<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">javascript<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<ol class=\"wp-block-list\" start=\"2\">\n<li><strong>Handling Form Submissions with URL Parameters:<\/strong> When users submit form data (e.g user profiles), the form data is often included in the URL as query parameters. If it contains special characters (such as &amp;, ?, or spaces), you should encode the URL parameters before sending them via GET or POST requests. This prevents unexpected behavior or errors due to invalid characters in the URL and ensures that the data is transmitted safely.<\/li>\n<\/ol>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-15\" data-shcb-language-name=\"HTML, XML\" data-shcb-language-slug=\"xml\"><span><code class=\"hljs language-xml\"><span class=\"hljs-tag\">&lt;<span class=\"hljs-name\">form<\/span> <span class=\"hljs-attr\">action<\/span>=<span class=\"hljs-string\">\"https:\/\/example.com\/search\"<\/span>&gt;<\/span>\n  <span class=\"hljs-tag\">&lt;<span class=\"hljs-name\">input<\/span> <span class=\"hljs-attr\">type<\/span>=<span class=\"hljs-string\">\"text\"<\/span> <span class=\"hljs-attr\">name<\/span>=<span class=\"hljs-string\">\"q\"<\/span> <span class=\"hljs-attr\">value<\/span>=<span class=\"hljs-string\">\"hello world\"<\/span>&gt;<\/span>\n  <span class=\"hljs-tag\">&lt;<span class=\"hljs-name\">input<\/span> <span class=\"hljs-attr\">type<\/span>=<span class=\"hljs-string\">\"submit\"<\/span> <span class=\"hljs-attr\">value<\/span>=<span class=\"hljs-string\">\"Search\"<\/span>&gt;<\/span>\n<span class=\"hljs-tag\">&lt;\/<span class=\"hljs-name\">form<\/span>&gt;<\/span><\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-15\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">HTML, XML<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">xml<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<ul class=\"wp-block-list\">\n<li>The form submits the data to &#8220;https:\/\/example.com\/search&#8221; when the submit button is clicked.<\/li>\n\n\n\n<li>The form data is encoded and sent to the server using the GET method, as it&#8217;s the default method for form submission when the action attribute is specified.<\/li>\n\n\n\n<li>The first input field contains a value of &#8220;hello world&#8221;. When the form is submitted, this value is encoded and appended to the URL as a query parameter. For example, the encoded URL might look like &#8220;https:\/\/example.com\/search?q=hello%20world&#8221;.<\/li>\n<\/ul>\n\n\n\n<ol class=\"wp-block-list\" start=\"3\">\n<li><strong>Sending Data via Ajax Requests:<\/strong> When sending Ajax requests to retrieve data from a server, you often include parameters in the URL. These parameters may contain special characters, so it&#8217;s necessary to encode the URL to ensure that your Ajax requests work well and avoids unexpected issues caused by special characters.<\/li>\n<\/ol>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-16\" data-shcb-language-name=\"JavaScript\" data-shcb-language-slug=\"javascript\"><span><code class=\"hljs language-javascript\"><span class=\"hljs-keyword\">const<\/span> inputWord = <span class=\"hljs-string\">\"hello world\"<\/span>;\n<span class=\"hljs-keyword\">const<\/span> encodedInputWord = <span class=\"hljs-built_in\">encodeURIComponent<\/span>(inputWord);\n<span class=\"hljs-keyword\">const<\/span> url = <span class=\"hljs-string\">\"https:\/\/sample.com\/api\/search?q=\"<\/span> + encodedInputWord;<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-16\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">JavaScript<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">javascript<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<h2 class=\"wp-block-heading\">When to Decode a URL<\/h2>\n\n\n\n<p>Here are some common scenarios when you might need to decode a URL:<\/p>\n\n\n\n<ol class=\"wp-block-list\">\n<li><strong>Processing URLs received from external sources:<\/strong> External sources (e.g API responses, user input) may provide encoded URLs. Decoding these URLs allows you to extract the original information and ensure that the data is correctly interpreted.<\/li>\n<\/ol>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-17\" data-shcb-language-name=\"JavaScript\" data-shcb-language-slug=\"javascript\"><span><code class=\"hljs language-javascript\"><span class=\"hljs-keyword\">const<\/span> encodedURL = <span class=\"hljs-string\">\"https%3A%2F%2Fsample.com%2Fsearch%3Fq%3Dhello%20world\"<\/span>;\n<span class=\"hljs-keyword\">const<\/span> decodedURL = <span class=\"hljs-built_in\">decodeURIComponent<\/span>(encodedURL);\n<span class=\"hljs-built_in\">console<\/span>.log(decodedURL); <span class=\"hljs-comment\">\/\/ Output: \"https:\/\/sample.com\/search?q=hello world\"<\/span><\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-17\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">JavaScript<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">javascript<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<ol class=\"wp-block-list\" start=\"2\">\n<li><strong>Displaying URLs in user interfaces:<\/strong> When displaying URLs in your application&#8217;s user interface, make sure they are in their original, human-readable format. Decoding the URLs ensures that they are displayed correctly to the user.<\/li>\n<\/ol>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-18\" data-shcb-language-name=\"JavaScript\" data-shcb-language-slug=\"javascript\"><span><code class=\"hljs language-javascript\"><span class=\"hljs-keyword\">const<\/span> encodedURL = <span class=\"hljs-string\">\"https%3A%2F%2Fsample.com%2Fsearch%3Fq%3Dhello%20world\"<\/span>;\n<span class=\"hljs-keyword\">const<\/span> decodedURL = <span class=\"hljs-built_in\">decodeURIComponent<\/span>(encodedURL);\n<span class=\"hljs-built_in\">document<\/span>.getElementById(<span class=\"hljs-string\">\"url\"<\/span>).textContent = decodedURL; <span class=\"hljs-comment\">\/\/ Output on the browser UI: \"https:\/\/sample.com\/search?q=hello world\"<\/span><\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-18\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">JavaScript<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">javascript<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<h2 class=\"wp-block-heading\">Tools for Encoding and Decoding URLs<\/h2>\n\n\n\n<p>Aside from the built-in functions in most programming languages used to encode and decode URLs, there are tools available online for doing basic encoding and decoding operations. Examples of such tools are <a href=\"https:\/\/urlencode.org\/\">urlencode.org<\/a>, <a href=\"https:\/\/www.urldecoder.org\/\">urldecoder.org<\/a>, and <a href=\"https:\/\/gochyu.com\/urldecode\">gochyu url encode<\/a>.<\/p>\n\n\n\n<figure class=\"wp-block-image\"><img data-recalc-dims=\"1\" decoding=\"async\" src=\"https:\/\/i0.wp.com\/paper-attachments.dropboxusercontent.com\/s_700D6D6369EC00B83D6370B9E7B96F2C4C2EED3CE9C1D47FD83F2547E8299331_1707905006326_encode%2Burl%2Btool.png?ssl=1\" alt=\"User interface of the urlencode.org website\"\/><\/figure>\n\n\n\n<p>These tools are simple to use: enter the URL you want to encode or decode and you get your result.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Conclusion<\/h2>\n\n\n\n<p>In conclusion, understanding the concepts of encoding and decoding URLs is essential for any web developer. These processes ensure data integrity, security and accuracy when transmitting data across the internet. Understanding when and how to encode or decode URLs allows developers to develop secure and reliable web apps that handle URL-related tasks efficiently.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>URL, which stands for Uniform Resource Locator, is an address to access resources on the internet. Each URL points to a unique resource on the web. URLs can sometimes contain special characters or need to be manipulated dynamically. In this article, we\u2019ll explore the modern techniques for working with URLs in JavaScript, and answer the [&hellip;]<\/p>\n","protected":false},"author":11,"featured_media":925,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"_acf_changed":false,"sig_custom_text":"","sig_image_type":"featured-image","sig_custom_image":0,"sig_is_disabled":false,"inline_featured_image":false,"_jetpack_memberships_contains_paid_content":false,"footnotes":""},"categories":[1],"tags":[3,110],"class_list":["post-915","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-blog-post","tag-javascript","tag-urls"],"acf":[],"jetpack_featured_media_url":"https:\/\/i0.wp.com\/frontendmasters.com\/blog\/wp-content\/uploads\/2024\/02\/encode-character-thumb.jpg?fit=1000%2C500&ssl=1","jetpack_sharing_enabled":true,"_links":{"self":[{"href":"https:\/\/frontendmasters.com\/blog\/wp-json\/wp\/v2\/posts\/915","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/frontendmasters.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/frontendmasters.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/frontendmasters.com\/blog\/wp-json\/wp\/v2\/users\/11"}],"replies":[{"embeddable":true,"href":"https:\/\/frontendmasters.com\/blog\/wp-json\/wp\/v2\/comments?post=915"}],"version-history":[{"count":10,"href":"https:\/\/frontendmasters.com\/blog\/wp-json\/wp\/v2\/posts\/915\/revisions"}],"predecessor-version":[{"id":934,"href":"https:\/\/frontendmasters.com\/blog\/wp-json\/wp\/v2\/posts\/915\/revisions\/934"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/frontendmasters.com\/blog\/wp-json\/wp\/v2\/media\/925"}],"wp:attachment":[{"href":"https:\/\/frontendmasters.com\/blog\/wp-json\/wp\/v2\/media?parent=915"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/frontendmasters.com\/blog\/wp-json\/wp\/v2\/categories?post=915"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/frontendmasters.com\/blog\/wp-json\/wp\/v2\/tags?post=915"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}