9

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.

2
  • Dupe: stackoverflow.com/questions/784313/… Commented Feb 8, 2010 at 23:11
  • Wouldn't it be simpler to assign the line break to a variable? Commented Jun 4, 2012 at 4:03

2 Answers 2

31

"\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>");
Sign up to request clarification or add additional context in comments.

5 Comments

Yep, chr(13) is '\r', not '\n'.
good news - it worked. but unfortunately only for the first linebreak (there's several in my string). any ideas?
you need to use the g flag in a regexp like in my answer, and not only take into account \r but \n too
Of course if you know the character code, you can always just use mystring.replace(String.fromCharCode(13), "<br>");
I like the third one above, nice solution. Is it not standard though to use <br /> instead of <br>? I could be wrong.
8
theString.replace(/\n|\r/g, '<br />')

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.