Pregunta

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?

¿Fue útil?

Solución

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;
}
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top