How to Encode a URL in JavaScript

Encoding ensures your URL is valid and can be safely sent over the internet. It's really easy, thanks to JavaScript. Here's how:

Why Encode URLs?

  • Spaces and special characters: URLs can't have spaces or special characters like !, #, %.
  • Safe transmission: Encoding converts these characters into a format that can be transmitted over the internet and stop you from having broken URLs.

How to

JavaScript provides a built-in function called encodeURIComponent() to encode a URL.

Let's say we have a string with special characters to include in a URL.

const myString = "Hello World! How's it going?";
const encodedString = encodeURIComponent(myString);

console.log(encodedString); 
// Output: Hello%20World%21%20How%27s%20it%20going%3F

If you want to encode an entire URL, including the query parameters, you can do it like this:

const myUrl = "https%3A%2F%2Fexample.com%2Fsearchq%3DHello%20World!";
const encodedQuery = encodeURIComponent(myUrl);

console.log(encodedQuery);
// Output: https://example.com/search?q%3DHello%20World%21

That's it! Now you know how to encode URLs in JavaScript to ensure they are safe for transmission.

JavaScript
Avatar for Niall Maher

Written by Niall Maher

Founder of Codú - The web developer community! I've worked in nearly every corner of technology businesses: Lead Developer, Software Architect, Product Manager, CTO, and now happily a Founder.

Loading

Fetching comments

Hey! 👋

Got something to say?

or to leave a comment.