2

I need to display a string containing \n using Jade and I want to convert those characters in <br>. I tried to do that in two ways:

- var s = 'text\nand\ntext';
p= string
p= string.replace(/\n/g, '<br />')

But in the first case I can't see spaces and with the second paragraph the HTML is escaped.

Gio Polvara
  • 23,416
  • 10
  • 66
  • 62

3 Answers3

2

use != instead of =

p!= string.replace(/\n/g, '<br />')

see the docs for more infos

zemirco
  • 16,171
  • 8
  • 62
  • 96
0

I solved it liked this:

- var text = '<script></script>\nhi';
p!= text.replace(/</g, "&lt;").replace(/>/g, '&gt;').replace(/\n/g, '<br />')

It doesn't escape html special characters but since I'm using <meta charset="utf-8"> it shouldn't be a problem.

Gio Polvara
  • 23,416
  • 10
  • 66
  • 62
  • Is the text supplied by a user? If so, you may need to worry about [XSS](https://en.wikipedia.org/wiki/Cross-site_scripting). User input should always be escaped. Otherwise they could do something malicious like inputting ``. Here's a [question](http://stackoverflow.com/q/3705356/1181886) that should get you started. If the text is safe, then disregard the above :) – Ryan Endacott Jul 11 '13 at 15:12
0

This was my solution:

    p
      striped = body.replace(/\r/g, '')
      paragraph = body.split(/\n{2,}/g)
      if paragraph.length
        each para in paragraph
          | <p>
          line = para.split(/\n/g)
          first = line.shift()
          | #{first}
          each li in line
            | <br />
            | #{li}
          | </p>

I throw away \r's and split on 2 or more \n's. If that results in a non-empty array, I loop the array and add a beginning <p> tag. Any lines with a single \n are split and looped with <br> tags, then it ends with a </p> tag. Lather, rinse, repeat. Bonus: strings are rendered properly escaped.

Jade is awesome! (as is regex)

Jaxon
  • 1
  • 3