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?
Related Topics
How to Replace multiple Texts at the same Time
Tutorial | 0 Comments
Rewrite Text Files with a fixed Line Length
Tutorial | 0 Comments
Repair Text Files with mixed Line Breaks
Tutorial | 0 Comments
Delphi: Multiline Caption for TLabel (at Run Time and Design Time)
Tutorial | 1 Comment
jQuery: Assign Action to Keyboard Keys (Keyboard Event)
Tip | 0 Comments
MySQL: Search and Replace directly in MySQL database
Tip | 1 Comment
MySQL: Line breaks in MySQL
Tip | 0 Comments
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.
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:
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:
The g at the end ensures that all occurrences are replaced.
2012-02-14 at 16:40