gpt4 book ai didi

javascript - jquery 删除新行然后用 block 元素包装文本节点

转载 作者:数据小太阳 更新时间:2023-10-29 04:05:39 25 4
gpt4 key购买 nike

我有一些这样的段落:

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

<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

关于javascript - jquery 删除新行然后用 block 元素包装文本节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5020434/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com