There is a reason that this:
decodeURI(decodeURI("\\n"));
Doesn't give a newline, yet this does:
JSON.parse('"\\n"');
It's because \n
is not actually a URI component (if a newline were URI encoded, it'd look like %0A
rather than \n
), and also because it's actually escaped.
Here are some demonstrations:
Demo 1: decodeURI("\n")
:
var newline = decodeURI("\n");
console.log("Line One" + newline + "Line Two");
You can see in the above that there is a newline in the console, between Line One
and Line Two
.
Demo 2: decodeURI(decodeURI("\\n"))
:
var newline = decodeURI(decodeURI("\\n"));
console.log("Line One" + newline + "Line Two");
Here, we can see that the escaped newline (\\n
) when decoded is just a newline string - newline
literally is the string "\n"
, not a newline. We can see proof of this in the next demonstration:
Demo 3: typeof decodeURI("\\n")
:
var newline = decodeURI("\\n");
console.log("Line One" + newline + "Line Two");
console.log(typeof newline);
And here we see that decodeURI("\\n")
returns just a string \n
, which for reasons unknown cannot be decoded by using decodeURI
twice, as you'll see here:
Demo 4: decodeURI(decodeURI("\\n"))
:
var newline = decodeURI("\\n");
var temp = decodeURI(newline);
console.log("Line One" + newline + "Line Two");
newline = temp;
console.log("Line One" + newline + "Line Two");
And here we can see that newline
and temp
are pretty much the same thing - the string "\n"
.
There is a reason that this code:
decodeURI("\n");
Actually returns a newline character as well - it is because before decodeURI
is used, "\n"
is already a newline character, so decodeURI
is redundant. See this:
var newlineString = "\n";
var newline = decodeURI(newlineString);
console.log("Line One" + newlineString + "Line Two");
console.log("Line One" + newline + "Line Two");
Here, both lines are separated by line breaks, which means that "\n"
doesn't actually get decoded at all - you don't need decodeURI
for this at all.
Hopefully this helps you!
Further reading: