Bruno Pigatto
Bruno Pigatto

Reputation: 67

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?

Upvotes: 1

Views: 6862

Answers (2)

Bhuwan
Bhuwan

Reputation: 16855

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>

Upvotes: 3

user9263373
user9263373

Reputation: 1074

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>

Upvotes: 0

Related Questions