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.
I solved it liked this:
- var text = '<script></script>\nhi';
p!= text.replace(/</g, "<").replace(/>/g, '>').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.
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)