JavaScript(JS) JS replace all line breaks with <br>

www.ig‮aeditfi‬.com

To replace all line breaks in a string with the HTML line break tag <br> in JavaScript, you can use the replace() method with a regular expression. Here's an example:

let str = "This is some\nmultiline\ntext.";

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

console.log(newStr); // Output: "This is some<br>multiline<br>text."

In this code, we define a string str that contains some line breaks. We use the replace() method with a regular expression /\n/g to replace all line breaks with the <br> tag. The g flag in the regular expression tells replace() to perform the replacement globally (i.e., on all matches).

Finally, we print the modified string newStr to the console using console.log(). The output should be the original string with all line breaks replaced with the <br> tag.