Replace '\n' with <br> in JavaScript

javascript

Solution

Use a regular expression (`RegExp`) literal and the "global" (`g`) modifier:

var val = recommend.replace(/\n/g, "<br />");

Or use a `RegExp` directly:

var val = recommend.replace(RegExp("\n","g"), "<br>");

Problem

I have `var recommend = 'I recommended Garden Solutions for this Tender Contracting on the basis of\n\n1)Top Scorer for tender\n2)Professional Experience in Building Services\n3)Approved Service Providers';` I want to replace `\n` with an HTML break and want to display it as below: I recommended Garden Solutions for this Tender Contracting on the basis of 1)Top Scorer for tender 2)Professional Experience in Building Services 3)Approved Service Providers I am using JavaScript's replace function ``` var val = recommend.replace("\n","<br>"); ``` But it's not working.

Original source

Related problems