udiboy1209
udiboy1209

Reputation: 1502

Why doesn't string.replace(/\n/g, '<br>') work with underscore.js?

I have a string, str with multi-line content in it, and I want to display it correctly on the HTML page with underscore.js using the above replace mentioned, like so:

<%= str.replace(/\n/g , '<br />' %>

But that doesn't work at all. It still prints the string in one line, and doesn't replace any \n with <br />. This, however, works perfectly:

<%= str.replace(/
/g , '<br />' %>

So why doesn’t the first way work, and is there a way to make it work for all cases?

Upvotes: 2

Views: 3854

Answers (1)

Ry-
Ry-

Reputation: 224859

You might need to double-escape backslashes if they’re used as an escape character by your template engine:

<% str.replace(/\\n/g , '<br />' %>

However, consider instead using CSS:

.some-content {
    white-space: pre-wrap;
}

Upvotes: 7

Related Questions