angry_kiwi angry_kiwi - 3 months ago 8x
jQuery Question

jquery remove new line then wrap textnodes with block element

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.

I want to remove the new lines and wrap each paragraph with the
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";

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>";