JS - 如何在一个中分割文本并放在2 <p>中

时间:2015-07-28 15:19:43

标签: javascript html paragraphs

我想要做的是扫描段落的innerHTML并找到段落标记之间的各种形式的换行符&lt; p&gt; / p&gt;:

<br>, <br />, or <br></br>

并删除它们。但是,在换行符的位置,我想使用document.createElement('p')将其前面的所有文本放入其自己的段落中,并将其后的所有文本放入另一个新段落中。

但是,如果有两个以上的换行符,中间没有文字,或只是空格,那么删除/忽略这个,不要把它放在自己的段落中。

这是我的意思的一个例子。以下是改动之前:

<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus convallis nisi sem, id gravida felis suscipit at. Sed ipsum felis, posuere ut turpis at, faucibus tempor dui. Nunc gravida sapien id velit vestibulum euismod.
<br />
<br />
Praesent vehicula rhoncus bibendum. Aenean tempus maximus aliquam. Nulla facilisi. Maecenas justo felis, faucibus ut posuere eget, fringilla et arcu. Sed ut pellentesque leo, a tincidunt tellus.</p>

这就是我想要改变的地方:

<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus convallis nisi sem, id gravida felis suscipit at. Sed ipsum felis, posuere ut turpis at, faucibus tempor dui. Nunc gravida sapien id velit vestibulum euismod.</p>

<p>Praesent vehicula rhoncus bibendum. Aenean tempus maximus aliquam. Nulla facilisi. Maecenas justo felis, faucibus ut posuere eget, fringilla et arcu. Sed ut pellentesque leo, a tincidunt tellus.</p>

这可以用 Javascript 吗?谢谢你的阅读!

1 个答案:

答案 0 :(得分:2)

For a first simple answer, try this:

s = prompt('Input HTML text example', '<p>...your text here...</p>');
if(!!s) {
  console.log(s.replace(/(<br ?\/?>)+/ig, '</p><p>'));
}

This method assumes that the original text is entered through some WYSIWYG editor, so:

  • we don't need to check if the whole text is wrapped in <p>...</p>
  • there's no matter with something like the </br> you cited

At the opposite if the text is rawly entered as HTML, we might encounter really anything, so it needs a totally different solution, based on a programmatically detailed analysis of the text.