Javascript 在contenteditable DIV中检测多个空行
给定此可编辑DIV:Javascript 在contenteditable DIV中检测多个空行,javascript,regex,Javascript,Regex,给定此可编辑DIV: <div contenteditable> First line Second line Third line Fourth line </div> 将其替换为一个空行: `\n\n` 到目前为止,我所拥有的: var text = div.textContent; text.replace(/ ??? /gm, '\n\n'); div.textContent = text; 如您所见,我不
<div contenteditable>
First line
Second line
Third line
Fourth line
</div>
将其替换为一个空行:
`\n\n`
到目前为止,我所拥有的:
var text = div.textContent;
text.replace(/ ??? /gm, '\n\n');
div.textContent = text;
如您所见,我不知道如何编写正则表达式来选择出现的多个空行。首先,我认为您要使用的regexp是
/\n\s+\n/
:一个换行符、任意大小的空格字符和另一个换行符
但是,您也需要保存结果:text=text.replace(…)
我想说一些相当简单的事情:
text.replace(/\n{3,}/gm, '\n\n');
或者,忽略行之间的空白(我认为这是您想要的):
顺便说一句,今天只有我还是JSFIDLE速度非常慢?@Šime Vidas:我也在经历这一点;有时它最近没有很好的响应。顺便说一句,
m
多行标志出于某种原因出现在这里。。。这很奇怪,因为我们在多行上进行匹配…@Šime Vidas:事实上,在这里,它与多行上的匹配没有太大关系,只是^
和$
的行为不是一行的开始/结束,而是完整的字符串。啊,对。谢谢你提供的信息。:)
var div = document.getElementsByTagName('div')[0],
text = div.textContent;
text = text.replace(/\n\s+\n/gm, '\n\n');
div.textContent = text;
text.replace(/\n{3,}/gm, '\n\n');
text.replace(/(\n\s*){3,}/gm, '\n\n');