我有一些这样的段落:
“这是第一段。r\r\n\n 这
是第二个有很多新行的
在 \n\n\n\n\n\n 和最后一段之后。
\n\r\r"
我想删除新行并将每个段落用<p>
标签。我期望输出如下:
<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>');
也许是这样的?
如果您发现该行在开头或结尾包含任何新行/回车符,请记住调用.trim()
在替换值之前首先在字符串上(使用此示例,d.trim().replace(...)
)
更稳健的解决方案
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 版本:
$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 http://www.ideone.com/1TRhh
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)