5

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.

TBE
  • 1,002
  • 1
  • 11
  • 32

1 Answers1

3

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!"));
GolezTrol
  • 114,394
  • 18
  • 182
  • 210
  • I need to do something else. How can i store a string with newline in it? For example: consider the following text: **text in line 1\n text in line2** How can i save it that `encodeURIComponent` will encode it to **text in line 1%0A text in line2** – TBE Nov 22 '15 at 08:19
  • That's exactly what that function does. I've added a sample/ – GolezTrol Nov 22 '15 at 09:30
  • Decoding it just works the other way. It would translate %0A back to the newline character (ASCII 10). Note that this character isn't *actually* `\n`. `\n` is just a way of embedding that character in a string. Basically that's just another encoding. There is [`decodeURIComponent`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/decodeURIComponent) too. – GolezTrol Nov 22 '15 at 09:40
  • so what if i would like to store a string that contains newline (before encoding) in a constant? how would i represent the newline so it will be encoded into %A0? – TBE Nov 22 '15 at 11:01
  • 1
    Then you use `"\n"`. I don't understand what I don't understand. :-s – GolezTrol Nov 22 '15 at 11:08