简体   繁体   中英

Replace '\n' with <br> in JavaScript

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.

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>");

By using the RegExp "\\n" you just replace the first occurrence. To replace all occurrences you need to add RegExp the modifier g .

So use the following, instead, to replace all occurrences:

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

Demo fiddle here .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM