最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Why doesn't string.replace(ng, '<br>') work with underscore.js? - Stack Overf

programmeradmin2浏览0评论

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?

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?

Share Improve this question edited May 5, 2014 at 12:07 udiboy1209 asked May 3, 2014 at 4:34 udiboy1209udiboy1209 1,5122 gold badges17 silver badges33 bronze badges 6
  • Oh sorry @muistooshort , I missed the = in this question. However, it is there in my HTML file. – udiboy1209 Commented May 4, 2014 at 13:16
  • What is a "string with multi-line content in it"? How is escaping (\ ) handled in there? – Bergi Commented May 4, 2014 at 13:55
  • @Bergi it is a string which when viewed in a general text editor will show content spanning multiple lines(with line breaks in it). But it es out in a single line on the webpage, because the browser collapses all the white spaces. As for the escaping, I think the \n is being removed or modified by something before it reaches javascript interpreter. However, minitech's answer below shows a way to avoid the problem of having to handle newlines and other whitespaces ourselves entirely. You basically tell the browser to take them literally and not ignore them. – udiboy1209 Commented May 4, 2014 at 14:43
  • @udiboy1209: Ah, right. What I meant to ask was how the (multiline?) template is stored - as a string inside a script, as a node of an html document? – Bergi Commented May 4, 2014 at 15:55
  • @Bergi , I basically stopped looking further into this issue after minitech's answer solved it. If you are curious, you can look at the source code of web plugin for beets on github. The problem I was referring to is in the index.html page of that plugin. – udiboy1209 Commented May 5, 2014 at 12:06
 |  Show 1 more ment

1 Answer 1

Reset to default 7

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;
}
发布评论

评论列表(0)

  1. 暂无评论