Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to replace line breaks with using JavaScript?
In this tutorial, we will learn how to replace line breaks in JavaScript strings with HTML <br> tags. This is commonly needed when converting plain text with line breaks to HTML format for proper display in web pages.
Using String replace() Method and RegEx
The replace() method with regular expressions is the most comprehensive approach as it handles all types of line breaks including \r (Windows), (Unix/Linux), and \r (Mac).
Syntax
sentence.replace(/(?:\r<br>|\r|<br>)/g, "<br>");
Here sentence is the string with line breaks, and the regular expression matches all three line break formats.
Example
<!DOCTYPE html>
<html>
<body>
<p id="original"></p>
<button onClick="replaceLineBreaks()">Replace Line Breaks</button>
<p id="result"></p>
<script>
let sentence = `JavaScript is a dynamic computer
programming language for web.
JavaScript can update and change both HTML and CSS`;
let original = document.getElementById("original");
let result = document.getElementById("result");
// Display original text
original.innerHTML = sentence;
function replaceLineBreaks() {
// Replace line breaks with <br> tags
let converted = sentence.replace(/(?:\r<br>|\r|<br>)/g, "<br>");
// Update the result paragraph
result.innerHTML = converted;
}
</script>
</body>
</html>
The regular expression /(?:\r matches all three types of line breaks and replaces them globally with
|\r|
)/g<br> tags.
Using split() and join() Methods
This method splits the string at line breaks into an array, then joins the array elements back together with <br> tags as separators.
Syntax
sentence.split("<br>").join("<br>");
Example
<!DOCTYPE html>
<html>
<body>
<p id="text"></p>
<button onClick="convertText()">Convert Line Breaks</button>
<script>
let sentence = `JavaScript is a dynamic computer
programming language for web.
JavaScript can update and change both HTML and CSS`;
let textElement = document.getElementById("text");
textElement.innerHTML = sentence;
function convertText() {
// Split at line breaks and join with <br> tags
let converted = sentence.split("<br>").join("<br>");
// Update the paragraph
textElement.innerHTML = converted;
}
</script>
</body>
</html>
The split(" method creates an array of substrings, and
")join("<br>") combines them back with <br> tags between each element.
Comparison
| Method | Handles All Line Breaks | Performance | Complexity |
|---|---|---|---|
| replace() with RegEx | Yes (\r , \r, ) |
Good | Medium |
| split() and join() | Only |
Good | Simple |
Conclusion
Use replace() with regular expressions for comprehensive line break handling across different platforms. The split() and join() method works well for simple cases with only line breaks.
