Table of Contents
URLs, standing for Uniform Resource Locators, are a way to identify a resource on the web.
You use URLs to visit websites, point to specific files, and to give names to IP addresses.
The web supports sending data via URLs by encoding it in the URL.
In this post, we'll learn how to encode URLs in JavaScript.
How to Encode URLs in JavaScript
The main point of encoding URLs is to make sure that the characters in the URL are safe to use.
This means that any characters that are unsafe must be escaped.
Thankfully, JavaScript offers built-in methods to encode URLs.
The first method, encodeURI
, takes an existing URL and encodes it safely.
JAVASCRIPTconst unsafeUrl = "https://www.google.com/search?q=javascript encodeURI";
const safeUrl = encodeURI(unsafeUrl);
console.log(safeUrl);
BASHhttps://www.google.com/search?q=javascript%20encodeURI
The encodeURI
method encoded the space in the URL as %20
, which made the entire URL safe.
If you want to encode query parameters, you can use the encodeURIComponent
method.
JAVASCRIPTconst unsafeParameters = "javascript encodeURI";
const safeUrl = "https://www.google.com/search?q=" + encodeURIComponent(unsafeParameters);
console.log(safeUrl);
BASHhttps://www.google.com/search?q=javascript%20encodeURI
Either way, the encodeURI
and encodeURIComponent
methods both help accomplish the same task, turning unsafe characters into safe ones, thereby encoding the URL.
Conclusion
In this post, we learned how to encode URLs in JavaScript.
Simply use either the encodeURI
or encodeURIComponent
methods to encode a string safely.
Thanks for reading and happy coding!
- How to Install Node on Windows, macOS and Linux
- Managing PHP Dependencies with Composer
- Create an RSS Reader in Node
- How to Serve Static Files with Nginx and Docker
- How to Set Up Cron Jobs in Linux
- How to deploy a PHP app using Docker
- How to deploy a MySQL Server using Docker
- How to deploy an Express app using Docker
- How to Scrape the Web using Node.js and Puppeteer
- Getting Started with Moment.js
- Using Push.js to Display Web Browser Notifications
- Getting Started with Vuex: Managing State in Vue