views:

669

answers:

2

I'm having a string which contains a chr(13) as linebreak. How can i replace it with eg. <br>? I tried mystring.replace("\n","<br>"); but it didn't work

Thanks in advance.

+6  A: 

"\n" is chr(10). I think you want "\r":

mystring.replace("\r", "<br>");

Updated: To replace ALL \r use a regular expression:

mystring.replace(/\r/g, "<br>");

If you want it to work with Windows, Unix and Mac style line breaks use this:

mystring.replace(/\r?\n|\r/g, "<br>");
Mark Byers
Yep, chr(13) is '\r', not '\n'.
Franci Penov
good news - it worked. but unfortunately only for the first linebreak (there's several in my string). any ideas?
Fuxi
you need to use the g flag in a regexp like in my answer, and not only take into account \r but \n too
Mic
@Fuxi: Are there any other characters that need replacing in your string? It's much better to fully describe your question at the beginning rather than changing it as you go.
Mark Byers
@Fuxi: I've updated my answer to be able to handle Windows, Unix *and* Mac style line endings! :)
Mark Byers
Of course if you know the character code, you can always just use mystring.replace(String.fromCharCode(13), "<br>");
Gyuri
+5  A: 
theString.replace(/\n|\r/g, '<br />')
Mic
Note that this will insert **two** `<br />`'s on Windows where the line ending is `\r\n`. See my solution for a fix.
Mark Byers