Consider whether you really want <br>
tags.
If you can use CSS instead
It's better to use white-space: pre-line
. See the MDN page, where it says
pre-line
Sequences of white space are collapsed. Lines are broken at newline characters, at <br>
, and as necessary to fill line boxes.
This is the same as the normal behaviour, except that newline characters turn into line breaks.
This ought to do what you want.
If you want <br>
tags
All of the existing answers here which give <br>
tags either don't escape the output for HTML (which can be dangerous), reimplement escaping logic, or leave a trailing newline.
This one is based on Palani's answer but does not leave a trailing newline, and also protects against foo
being nullish or false.
each line in (foo || '').split('\n').slice(0, -1)
= line
br
= (foo || '').split('\n').pop()
I don't love this solution but I think it's preferable to the others, if you want <br>
tags.
If you might be putting large strings through it, it might be a good idea to make a temporary variable for the result of the split
so it's not done twice.