Converting New Lines To Paragraph/br Html Tags, Can This Be A Single Regex?
Solution 1:
There are two different replacement strings. So it's impossible to make it in single replace call.
But second replace() can be changed to more effective plain string substitution.
content = '<p>' + content.replace(/\n([ \t]*\n)+/g, '</p><p>')
.replace('\n', '<br />') + '</p>';
So, there's single regexp. :)
Update
Javascript bluffed me. String replace
handles only first occurrence.
See How to replace all occurrences of a string in JavaScript?
There are also given several possible workaround implementations of replaceAll
.
Solution 2:
I was facing a similar requirement - to mimic the wpautop functionality into javascript (for use in the theme customizer).
So here is my approach to the problem:
First, replace the case when there are two line breaks.
to = to.replace(/\n{2}/g, ' </p><p>');
Then, replace the case when there are only one line breaks left.
to = to.replace(/\n/g, ' <br />');
And lastly wrap the whole content in a <p> tag
to = '<p>' + to + '</p>';
I used the because my styling implied margin after the paragraph. You can omit them if you don't need them. Also, one drawback is that the single line breaks are inserted in the beginning of the next paragraph, but this is something I can live with that.
Post a Comment for "Converting New Lines To Paragraph/br Html Tags, Can This Be A Single Regex?"