How to replace line breaks with br tag using JavaScript ?
There are multiple ways to replace line breaks with <br>
tag using JavaScript:
Method 1: Using Regular Expression
We can use the replace()
method with a regular expression to replace all occurrences of line breaks with <br>
tag. Here's an example:
let text = "This is a\nmultiline\ntext.";
let replacedText = text.replace(/(?:\r\n|\r|\n)/g, '<br>');
console.log(replacedText);
Output:
This is a<br>multiline<br>text.
In the above example, we first define a string text
with multiple line breaks. Then we use the replace()
method with a regular expression /(?:\r\n|\r|\n)/g
to match all occurrences of line breaks (including Windows, Mac, and Unix line breaks) and replace them with <br>
tag.
Method 2: Using String Split and Join
We can also split the string into an array of lines using the split()
method and then join them back with <br>
tag using the join()
method. Here's an example:
let text = "This is a\nmultiline\ntext.";
let lines = text.split(/\r\n|\r|\n/);
let replacedText = lines.join('<br>');
console.log(replacedText);
Output:
This is a<br>multiline<br>text.
In the above example, we first define a string text
with multiple line breaks. Then we use the split()
method with a regular expression /(\r\n|\r|\n)/
to split the string into an array of lines. Finally, we use the join()
method to join the lines back with <br>
tag.
Method 3: Using Template Literals
We can also use template literals to replace line breaks with <br>
tag. Here's an example:
let text = "This is a\nmultiline\ntext.";
let replacedText = text.replace(/\r?\n/g, () => `<br>`);
console.log(replacedText);
Output:
This is a<br>multiline<br>text.
In the above example, we first define a string text
with multiple line breaks. Then we use the replace()
method with a regular expression /\r?\n/g
to match all occurrences of line breaks (including Windows and Unix line breaks) and replace them with <br>
tag using a template literal.