How to replace space with %20 in JavaScript

This tutorial is going to be useful for those who are dealing with URL. Because this tutorial will help you to learn how to replace space with %20 in JavaScript easily. You can replace a space with percent twenty in many ways. But as this JavaScript tutorial is mainly focused for URL formatting thus I will mention the best way to achieve your goal.

In many cases, it has been seen that you are having spaces in your URL. And somehow you need to replace those whitespaces with %20.

Here I am going to give you a short example when I have first faced the problem of this space in my URL.

Play Selected Part of a Video in javaScript

I had to share a link like this https://www.example.com/index.php?from=name



Now suppose you want the full name as a parameter. Then the URL might look like this

https://www.example.com/index.php?from=alex smith

And in many platforms, the URL will be considered as https://www.example.com/index.php?from=alex

As the surname is not attached with the first name and so that will be considered separated from the URL

One example is :

In WhatsApp, the URL pattern will not consider the last name attached with the URL.

In this situation, if you can replace space with %20 then you will achieve your goal to make the URL format correct for you.

Replace space with %20 in JavaScript

You can replace a space with %20 with two different methods.

  • string.replace() method
  • encodeURIComponent(url.trim()) method

Both of the above methods can be used to replace white spaces with %20.

var string="my strings";
document.write(encodeURIComponent(string.trim()));

Output:

my%20strings

Next, another way is:

var string="my strings";
document.write(string.replace(/ /g, '%20'));

Output:

my%20strings

Don’t think that you have achieved your goal. Because encodeURIComponent(string.trim()) this method has some problem with URL formatting. Just take a look at these below examples

var url="https://www.codespeedy.com/my video";
  document.write(encodeURIComponent(url.trim()));

The output will be like this:

https%3A%2F%2Fwww.codespeedy.com%2Fmy%20video

This is the problem. As it will also replace the backslash and colon.

But if you use the replace method it will work fine for you

var url="https://www.codespeedy.com/my video";
  document.write(url.replace(/ /g, '%20'));

Output:

https://www.codespeedy.com/my%20video

I hope you have got my point.

You may also read,

Leave a Reply

Your email address will not be published. Required fields are marked *