Javascript regex for replacing newlines from textarea with <p> tags

See chapter. I need a regex to replace newlines with tags <p>.

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 that did not work.

Any ideas? Thank!

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

Are you sure you want to use user input as HTML? What if they put HTML special characters, even <script>alert('hello!');</script>? If you want to process input characters in 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 the 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);
}
+4
source

Try this snippet:

var html = '<p>'+notes.replace(/\r/g, '').replace(/\n([^\n]+)/g, '</p>\1<p>')+'</p>';
0

Source: https://habr.com/ru/post/1773221/


All Articles