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.
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
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.
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()));
Next, another way is:
var string="my strings"; document.write(string.replace(/ /g, '%20'));
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://codespeedy.com/my video"; document.write(encodeURIComponent(url.trim()));
The output will be like this:
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://codespeedy.com/my video"; document.write(url.replace(/ /g, '%20'));
I hope you have got my point.
You may also read,