正则表达式 - 在 javascript 中用单行替换多换行符 [英] regex - replace multi line breaks with single in javascript
问题描述
这是javascript中的某种变量内容:
this is some kind of variable content in javascript:
<meta charset="utf-8">
<title>Some Meep meta, awesome</title>
<-- some comment here -->
<meta name="someMeta, yay" content="meep">
</head>
我想将多换行符(未知数)减少为单个换行符,同时保留其余格式.这应该在带有 regex
的 javascript
中完成.
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
.
我在使用制表符或保留格式时遇到问题.
I have problems with the tabulator or to keep the format.
推荐答案
试试这个:
text.replace(/
s*
/g, '
');
这基本上是寻找两个换行符,中间只有空格.然后它用一个换行符替换那些.由于全局标志 g
,这对于每个可能的匹配都会重复.
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.
是否可以用双换行代替单换行
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(/
s*
s*
/g, '
');
如果您想在其中一行中保留空格(无论出于何种原因),您也可以这样做:
If you want to maintain the whitespace on one of the lines (for whatever reason), you could also do it like this:
text.replace(/(
s*?
)s*
/, '$1');
这篇关于正则表达式 - 在 javascript 中用单行替换多换行符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!