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

christian picture christian · Mar 17, 2012 · Viewed 14.5k times · Source

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

Any help would be appreciated.

Answer

alex picture alex · Mar 17, 2012

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.