I have a string and I need to replace %2f
with /
, except in http://
.
Example:
var str = "http://locahost%2f";
str = str.replace(/%2f/g, "/");
Somehow I got str
to output http:/locahost/
.
Thanks in advance!
I have a string and I need to replace %2f
with /
, except in http://
.
Example:
var str = "http://locahost%2f";
str = str.replace(/%2f/g, "/");
Somehow I got str
to output http:/locahost/
.
Thanks in advance!
You should use decodeURIComponent
or decodeURI
functions to decode encoded strings like yours. For example, decodeURIComponent("http://locahost%2f")
will return http://localhost/
.
That being said, decodeURIComponent
should be used to decode components of a URI and not a full URI like http://locahost/
.
You should look at this answer, it explains what is the difference between decodeURIComponent
and decodeURI
and when each should be used.
As the first /
are not encoded, it makes it difficult to find a Javascript functions doing exactly what you want. A working solution to decode your %2f
after http://
would be to use String.prototype.split
.
Working example:
var encoded = "http://localhost%2f";
var encodedArray = str.split("://");
var decoded = encodedArray[0] + "://" + encodedArray[1].replace(/%2f/g, "/");
This should work:
str = str.replace("%2f", "/");