简体   繁体   English

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

[英]regex - replace multi line breaks with single in javascript

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 javascript with a regex .这应该在带有regex javascript完成。

I have problems with the tabulator or to keep the format.我对制表符有问题或要保留格式。

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/, '$1');
myText = myText.replace(/\n{2,}/g, '\n');​​​​​​​

看演示

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小提琴演示

要替换所有额外的换行符并只留下一种用法:

myText = myText.replace(/\n\n*/g,'\r\n');​​​​​​​

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM