Search code examples
javascripturl-encodingurldecode

In NODE.JS, the newline code (%0A) will decode back to what character?


I have a pretty simple question, but a few simple googling and stachexchange queries were not able to answer it, so i guess i'm missing something here.

Here are my simplified parameters:

  1. I'm using Javascript.
  2. I have a text that needs to get URLEncoded and the text have more than 1 line.

My question is: What is the character for newline before the text get encoded? (I know that after the encoding the newline will be encoded into %0A)

I guess asking "What char is decoded when decoding %0A" will be the same.


Solution

  • Those codes consist of a percent sign, followed by a two character hexadecimal number representing a byte value.

    So in this case, the byte value is 0A, representing the ASCII newline character. This is commonly written as \n inside strings in JavaScript (and others, like PHP).

    But I think your question suggests you want to do some search and replace for this character. I would not do that, since there can be other characters too that need encoding. Instead, use the function encodeURIComponent, which can encode the entire string for you. There is encodeURI as well, but in your case, I think the first is more appropriate.

    This example shows how special characters (newline, space, and others) are encoded to an url-friendly format. Note that the diacritic é translates to the two bytes of its UTF-8 representation.

    document.write(encodeURIComponent("Normal text\nEéy, check the specials: /, + and \t!"));