I have some paragraphs like this:
"This is the first para. r\r\n\n This is the second one with lot of new line after \n\n\n\n\n\n And the last para. \n\r\r"
I want to remove the new lines and wrap each paragraph with the <p>
tag. I'm expecting output as follows:
<p>This is the first para.</p>
<p>This is the second one with lot of new line after</p>
<p>And the last para.</p>
var d = "line 1\n\nline2\n\n\n\nline3";
$('body').append('<p>'+d.replace(/[\r\n]+(?=[^\r\n])/g,'</p><p>')+'</p>');
something like this perhaps?
If you find the line contains any new lines/carriage returns at the beginning or end, remember to call a .trim()
on the string first before replacing the values (using this example, d.trim().replace(...)
)
More robust solution
function p(t){
t = t.trim();
return (t.length>0?'<p>'+t.replace(/[\r\n]+/,'</p><p>')+'</p>':null);
}
document.write(p('this is a paragraph\r\nThis is another paragraph'));
PHP Version:
$d = "paragraph 1\r\nparagraph 2\r\n\r\n\r\nparagraph3";
echo "<p>".preg_replace('/[\r\n]+/','</p><p>',$d)."</p>";
http://www.ideone.com/1TRhh
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