开发者

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开发者_JAVA百科 = notes.replace(pattern, "</p>$3<p>");
var html = notesRet;

But it didn't work.

Any ideas? Thanks!


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);
}


Try this snippet:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜