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. \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
How about this?
var output = $();
$.each("This is the first para. \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".split(/[\n\r]+/g), function(i, el) {
if (el) {
output = output.add($('<p>' + el + '</p>'));
}
});
This creates a jQuery selection containing the p
elements.
you can try something like this:
function parse_it(yourstring, tagname){
yourstring.replace(/[\r\n]+/g, '#x#');
paragraphs = yourstring.split('#x#');
pars = "";
for(var i=0; i<paragraphs.length; i++)
pars += '<'+tagname+'>'+paragraphs[i]+'</'+tagname+'>';
return pars;
}
var parsedstring = parse_it("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", 'p');
replace regex: /(?:[\r\n]*)(.+)(?:[\r\n]*)/
with: <p>$1</p>
context: global
In Perl its: s/ (?:[\r\n]*) (.+) (?:[\r\n]*) /<p>$1<\/p>/xg
精彩评论