1

I have some strings which have line breaks inside, in console they are shown with breaks:

string1:
test 1
test 2
test 3

I need to split the string and make something like this:

string1:
<p>test 1</p>
<p>test 2</p>
<p>test 3</p>

For most of them the next code works:

string1.split('\n\n').join('</p><p>')

but for some strings this doesn't work, so I could assume they have some other line breaks, for example '\r\n'

Can I somehow see all line breaks as they are? I mean as something like the next:

string1:
test 1\n\n
test 2\n\n
test 3\n\n

2 Answers2

1

Isn't it only a single newline:

test1\ntest2\ntest3

Also, you can use replace instead of split-join:

string1.replace(/\r\n|\n\r|\n|\r/g, '</p><p>')

Make sure to add on the start and end:

'<p>' + string1.replace('\n', '</p><p>') + '</p>'
Solomon Ucko
  • 5,724
  • 3
  • 24
  • 45
1

It would be a good case for a regular expression. Sometimes line breaks have only \n sometimes \r\n. Have a look at the answer here: Match line break with regular expression and the documentation on replace() in JavaScript: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace

chrwahl
  • 8,675
  • 2
  • 20
  • 30