-3

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!

jeerbl
  • 7,537
  • 5
  • 25
  • 39
HK2012
  • 1
  • 2
  • 2
    Why do you have to do this? Can you post more code? There probably is a better way. –  Mar 28 '16 at 22:34
  • The code works fine, If you're doing this in a bookmarklet, make sure you're escaping your code properly. – Ultimater Mar 28 '16 at 22:36
  • 1
    You could look for the `://` string and replace everything after that string. Using string `split` method for example. – jeerbl Mar 28 '16 at 22:36
  • 3
    By the way, when I execute your code in Firefox console, it gives me the good output. Are you sure nothing is missing in your question? – jeerbl Mar 28 '16 at 23:03
  • 1
    This question is fishy. Why did you even mention that http:// should be excluded? It obviously doesn't contain the string "%2f" – 4castle Mar 28 '16 at 23:12
  • Any answer actually answered your question? – jeerbl Aug 17 '16 at 08:26

2 Answers2

0

What should be used

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.

A workaround

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, "/");
Community
  • 1
  • 1
jeerbl
  • 7,537
  • 5
  • 25
  • 39
  • I don't understand why splitting is necessary. The string "%2f" doesn't exist in "http://" – 4castle Mar 28 '16 at 23:16
  • Then what is the question about? – jeerbl Mar 29 '16 at 08:19
  • 1
    I honestly have no idea what the question is. It seems nothing is broken in the first place. Your answer is great! But the question is unanswerable because the output is already correct. – 4castle Mar 29 '16 at 13:28
-3

This should work:

str = str.replace("%2f", "/");
Richard Hayes
  • 145
  • 1
  • 2
  • 8