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, '&').replace(/</g, '<').replace(/>/g, '>')
.replace(/"/g, '"').replace(/'/g, ''');
);
}
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>';
精彩评论