正则表达式 - 在 javascript 中用单行替换多换行符

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10965433/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 03:48:35  来源:igfitidea点击:

regex - replace multi line breaks with single in javascript

javascriptregexreplace

提问by mrzmyr

this is some kind of variable content in javascript:

这是 javascript 中的某种变量内容:

    <meta charset="utf-8">

    <title>Some Meep meta, awesome</title>




    <-- some comment here -->
    <meta name="someMeta, yay" content="meep">

</head>

I want to reduce the multi line breaks (unknown number) to a single line break while the rest of the formatting is still maintained. This should be done in javascriptwith a regex.

我想将多换行符(未知数)减少为单个换行符,而其余格式仍然保留。这应该javascript用一个regex.

I have problems with the tabulator or to keep the format.

我对制表符有问题或要保留格式。

回答by poke

Try this:

尝试这个:

text.replace(/\n\s*\n/g, '\n');

This basically looks for two line breaks with only whitespace in between. And then it replaces those by a single line break. Due to the global flag g, this is repeated for every possible match.

这基本上寻找两个换行符,中间只有空格。然后它用一个换行符替换那些。由于全局标志g,对于每个可能的匹配项都会重复此操作。

edit:

编辑:

is it possibile to leave a double line break instead of a single

是否可以留下双换行符而不是单行符

Sure, simplest way would be to just look for three line breaks and replace them by two:

当然,最简单的方法是查找三个换行符并将它们替换为两个:

text.replace(/\n\s*\n\s*\n/g, '\n\n');

If you want to maintain the whitespace on one of the lines (for whatever reason), you could also do it like this:

如果您想在其中一行中保留空格(无论出于何种原因),您也可以这样做:

text.replace(/(\n\s*?\n)\s*\n/, '');

回答by mVChr

myText = myText.replace(/\n{2,}/g, '\n');???????

See demo

看演示

回答by David says reinstate Monica

Given the following (remember to encode HTML entities such as <, >and (among others, obviously) &):

鉴于以下内容(请记住对 HTML 实体进行编码,例如<,>和 (显然,还有其他)&):

<pre>
&lt;head&gt;

    &lt;meta charset="utf-8"&gt;

    &lt;title&gt;Some Meep meta, awesome&lt;/title&gt;




    &lt;-- some comment here -->
    &lt;meta name="someMeta, yay" content="meep"&gt;

&lt;/head&gt;
</pre>
<pre>
</pre>?

The following JavaScript works:

以下 JavaScript 有效:

var nHTML = document.getElementsByTagName('pre')[0].textContent.replace(/[\r\n]{2,}/g,'\r\n');
document.getElementsByTagName('pre')[1].appendChild(document.createTextNode(nHTML));?

JS Fiddle demo.

JS小提琴演示