在可满足内容的DIV中检测多个空行

Detect multiple empty lines in contenteditable DIV

本文关键字:检测 DIV 可满足      更新时间:2023-09-26

给定这个可编辑的div:

<div contenteditable>
    First line
    Second line
    Third line    

    Fourth line
</div>

现场演示: http://jsfiddle.net/Mpvyk/1/

注意"第三行"answers"第四行"之间的3个空行。我想用一个空行代替这3个空行。

那么,在DIV中,对于所有出现this:

''n' (zero or more spaces or tabs) ''n' (zero or more spaces or tabs) ''n' etc.

将其替换为一个空行:

`'n'n`

目前为止我有什么:

var text = div.textContent;
text.replace(/ ??? /gm, ''n'n');
div.textContent = text;

如您所见,我不知道如何编写正则表达式来选择出现多个空行

首先,我认为你之后的regexp是/'n's+'n/:一个换行符,任意数量的类似空格的字符和另一个换行符。

但是你也需要保存结果:text = text.replace(...) .

var div = document.getElementsByTagName('div')[0],
    text = div.textContent;
 text = text.replace(/'n's+'n/gm, ''n'n');
div.textContent = text;
http://jsfiddle.net/Mpvyk/2/

我会用一些相当简单的:

text.replace(/'n{3,}/gm, ''n'n');

或者,忽略行与行之间的空白(我认为这是你想要的):

text.replace(/('n's*){3,}/gm, ''n'n');