Why doesn't this work?
decodeURI('\n') => newline;
decodeURI("\\n") => '\n', thus presumably...
decodeURI(decodeURI("\\n")) // => gives '\n' instead of newline
But this does?
JSON.parse('"\\n"') // => newline
Point here is to be able to build a \* character string, then convert it to its actual character via decodeURI.
I'd like to avoid using JSON.parse if possible.
I realize the way I approached this was confusing. A better question would have been to ask how decodeURI and JSON.parse do their conversion from the string literal to the resolved character and if there was something more direct.
decodeURI('\n') => newline; thus presumably
In your code, \n
is a newline character before it even gets to decodeURI. Backslashes have meaning in a string literal in JavaScript.
decodeURI(decodeURI("\\n")) // => gives '\n' instead of newline
In this example, you've escaped the backslash with another backslash. Therefore, instead of passing a newline character to decodeURI()
, you're passing the text of a backslash character and an 'n' character. Neither of these have special meaning in URIs and thus the output of this decodeURI()
is the same as its input. Doing it twice of course makes zero difference. I don't really follow what your point is here.
But this does?
JSON.parse('"\\n"') // => newline
Again, try to unpack it is what you're doing here. The first backslash escapes the next, leaving you with an actual backslash in the string. So, the real string is "\n"
. If you JSON.parse()
this, the parser first interprets that you're dealing with a string literal. Then, it decodes \n
to a newline character. That's why it outputs just a newline.
Point here is to be able to build a * character string, then convert it to its actual character via decodeURI.
decodeURI
has absolutely nothing to do with that.