00 Votes

JavaScript: Replace line break

Question by SimplyMe | 2012-02-12 at 19:18

I have a string in JavaScript and I would like to replace in this string all new lines with <br>. So far, I have developed the following approach:

str.replace("\n", "<br>");

For whatever reason, that does not seem to be working. What can be the reason?

ReplyPositiveNegative
5Best Answer5 Votes

Depending on the operating system, other characters can be used as a line break. On Windows, it is #13#10 (\r\n), Unix or Linux are only using #10 (\n) and macOS #13 (\r). So, if you have only replaced \n, for example, you will not get it work on Windows.

Try it with this solution:

str.replace(/\n|\r/g, "<br>");

This regular expression causes, that really all species of line breaks are replaced.

Besides, if you stay in your solution above, only the first occurrence of \n will be replaced. Here, it is also better, to use a regular expression:

str.replace(/\n/g, "<br>");

The g at the end ensures that all occurrences are replaced.
2012-02-14 at 16:40

ReplyPositive Negative
Reply

Related Topics

Important Note

Please note: The contributions published on askingbox.com are contributions of users and should not substitute professional advice. They are not verified by independents and do not necessarily reflect the opinion of askingbox.com. Learn more.

Participate

Ask your own question or write your own article on askingbox.com. That’s how it’s done.