An app I am working on has the user enter content in plaintext that will later be displayed as HTML. To make the user's content display as nicely as possible, we transform the content as follows:
Any blocks of text delimited by two or more new line characters are wrapped in <p> tags. The new line characters (and any whitespace in-between) are stripped out.
Any single new line characters (along with surrounding whitespace) are replaced by a <br /> tag.
I'm currently achieving this by putting the the text through two regex replacements but was wondering if it could possibly be consolidated to one. Here's what I have right now (JavaScript):
// content holds the text to process
content = '<p>' + content.replace(/\n([ \t]*\n)+/g, '</p><p>')
.replace(/\n/g, '<br />') + '</p>';
The RegEx is used with the replace() method to replace all the line breaks in string with <br>. The pattern /(\r\n|\r|\n)/ checks for line breaks. The pattern /g checks across all the string occurrences.
In order to replace all line breaks from strings replace() function can be used.
We are using the String. replace() method of regex to replace the new line with <br>. The String. replace() is an inbuilt method in JavaScript that is used to replace a part of the given string with another string or a regular expression.
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.
So you'll have to either use modern replaceAll
function
or fall back to second regexp
.replace(/\n/g, '<br />') + '</p>';
or to use String replaceAll
polyfill for legacy browsers.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With