简体   繁体   中英

Replace \n with <br> is not working

In my mongoDB:

description: "Test\n\nTest"

When I try to show it in my ejs file the text ignores de "\\n"

Test Test

My HTML

<div id="description">
    <%= test.description %>
</div>

I tried to fix this using this code :

var desc = $('#description').text();
desc.replace("\n", "<br>");

$('.description').text(desc);

Also tried:

desc.replace(/(?:\r\n|\r|\n)/g, '<br />');

and:

desc.split("\n").join("<br />");

None of this worked

If I print var desc = $('#description').text(); in the Chrome console, it shows this:

              Test

Test

What I'm doing wrong and how do i fix this?

Use html() instead of text() as you want to change the HTML markup.... text() will ignore the <br> tags

Also you are just replacing the value not updating it.....need to put the replaced value in the desc variable by

desc = desc.replace(/\n/g, "<br>");

Also desc.replace("\\n", "<br>"); will just replace the first \\n match

Stack Snippet

 var desc = "Test\\n\\nTest" desc = desc.replace(/\\n/g, "<br>"); $('#description').html(desc); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="description"></div> 

Using your code, desc.split("\\n").join("<br />"); works fine for me.

 var desc = $('#description').text(); console.log("original text = " + desc); desc = desc.split("\\n").join("<br />"); console.log("using split/join = " + desc); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="description"> Here is the contents of the div with line breaks in it. </div> 

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