Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript regular expression to replace newlines from textarea with wrapping <p> tags

See title. I need a regular expression to replace newlines with wrapping <p> tags.

I tried this:

var pattern = new RegExp("{(?:^|(?:\x0d\x0a){2,}|\x0a{2,}¦\x0d{2,})(.+?)(?=(?:(\x0d\x0a){2,}|\x0d{2,}|\x0a{2,}|$))}");
var notesRet = notes.replace(pattern, "</p>$3<p>");
var html = notesRet;

But it didn't work.

Any ideas? Thanks!

like image 330
Allen Gingrich Avatar asked May 23 '26 12:05

Allen Gingrich


1 Answers

notes= notes.replace(/\r/g, '');  // normalise IE CRLF newlines
var html= '<p>'+notes.replace(/\n{2,}/g, '</p><p>')+'</p>';

Do you really want to take user input as HTML, though? What if they put HTML-special characters in, even <script>alert('hello!');</script>? If you want to treat input characters as plain text you will need HTML-escaping:

function encodeHTML(s) {
    return (s
        .replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;')
        .replace(/"/g, '&quot;').replace(/'/g, '&#39;');
    );
}

notes= encodeHTML(notes).replace(...

Or, perhaps more cleanly, do it with DOM:

var ps= notes.replace(/\r/g, '').split(/n{2,}/);
for (var i= 0; i<ps.length; i++) {
    var p= document.createElement('p');
    p.appendChild(document.createTextNode(ps[i]));
    someParentElement.appendChild(p);
}
like image 71
bobince Avatar answered May 26 '26 00:05

bobince



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!