10

I am creating comments from user input and rendering them using Mustache.js after a user clicks 'submit'. I realize I can replace user input line breaks (\n) with <br/> to render as HTML breaks, such as

myString.replace(/\n/g, '<br />');

and I realize I can make Mustache not escape HTML by using triple brackets

{{{myString}}}

However, I would like to escape all user HTML as Mustache would typically do with double braces {{ ... }}, with the exception of allowing line breaks with <br/>

What is the best way to do this? I can replace the line breaks after it has been rendered, but that seems like a very inefficient solution, and I'm thinking there has to be a better way.

Ryan
  • 17,511
  • 23
  • 63
  • 88

2 Answers2

14

Option 1 - Use a pre tag:

It's actually best (or efficient) that you wrap text in a <pre></pre> tag, which will preserve the white space in the text.

https://developer.mozilla.org/en-US/docs/Web/HTML/Element/pre

And enable word-wrap

How do I wrap text in a pre tag? - http://jsfiddle.net/X5ZY7/


Option 2 - Split your string into lines, and use a mustache each:

comment = userComment.split("\n")


{{#comment}}
    {{comment}}<br/>
{{/comment}}


Option 3 - Manually escape your string using your favorite method before injecting the
tags:

var div = document.createElement("div")
div.textContent = comment
comment = div.innerHTML.replace(/\n/g, "<br/>")


{{{comment}}}
Community
  • 1
  • 1
Matt Esch
  • 22,661
  • 8
  • 53
  • 51
  • I really don't want to preserve all white space, but rather just line breaks. I setup a quick test as well, and it doesn't seem that I can get
     tags to actually word wrap (even when it's explicitly set), so the text goes outside the boundaries and flow the the DOM elements.
    – Ryan Jan 22 '14 at 02:18
  • I think option 2 or 3 is more what I'm looking for. Thanks for the suggestions Matt! – Ryan Jan 23 '14 at 06:28
  • 2
    Option 2 should be ` {{#comment}} {{.}}
    {{/comment}} `
    – Darren Newton Jun 13 '15 at 03:25
1

If you're looking to add line breaks to a textarea you need to replace \n with &#13;&#10;

blented
  • 2,699
  • 2
  • 23
  • 17
  • if I use this `text.replace(/\n\r?/g, ' ');` should I render like `` ? but still not change line ... – user1775888 Jun 24 '16 at 03:20