jquery删除新行,然后用block元素包装textnodes [英] jquery remove new line then wrap textnodes with block element

查看:151
本文介绍了jquery删除新行,然后用block元素包装textnodes的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些这样的段落:


这是第一段.r \\\\\
是第二个在\ n \\ n \\ n \\ n \\ n \\ n \\ n \\ n \\ n \ n \\ n \ n \ n之后有很多新行
而且最后一个$。
\ n \ r \ r

"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>包装每个段落; 标签。我期望输出如下:

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>');

或许这样的事情?

如果你发现该行在开头或结尾包含任何新的行/回车,请记住在更换值之前首先在字符串上调用 .trim()(使用这个例子, d.trim()。replace(...)

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(...))

更强大的解决方案

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版本:


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

这篇关于jquery删除新行,然后用block元素包装textnodes的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆