Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript Replacing All Instances of New Line Character ASCII (13) with "\r\n"?

How can I replace all instances of a newline character ASCII code (13) in a string with "\r\n"?

Any help would be appreciated.

like image 518
christian Avatar asked Mar 16 '12 23:03

christian


People also ask

What does \r and \n mean?

\n means new line. It means that the cursor must go to the next line. \r means carriage return. It means that the cursor should go back to the beginning of the line.

Is there an ASCII for new line?

The ASCII character code 10 is sometimes written as \n and it is sometimes called a New Line or NL . ASCII character 10 is also called a Line Feed or LF .

What does \r mean in HTML?

The \r metacharacter matches carriage return characters.

How do you make a new line in JavaScript?

The newline character is \n in JavaScript and many other languages. All you need to do is add \n character whenever you require a line break to add a new line to a string.


1 Answers

You can use this to do it...

str = str.replace(new RegExp(String.fromCharCode(13), 'g'), '\r\n');

Naturally, if you don't need to pass a variable to get the char code (or if it's not clearer), use the character in a regex literal, e.g. /\r/g.

like image 163
alex Avatar answered Nov 15 '22 22:11

alex