正则表达式 - 在javascript中用单个替换多个换行符 [英] regex - replace multi line breaks with single in javascript

查看:497
本文介绍了正则表达式 - 在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>

我希望将多行换行符(未知数字)减少到单个换行符,而剩下的格式仍然保持不变。这应该在 javascript 中使用 regex 完成。

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(/\n\s*\n/g, '\n');

这基本上会查找两个换行符,其间只有空格。然后它通过单个换行符取代它们。由于全局标志 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(/\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');

这篇关于正则表达式 - 在javascript中用单个替换多个换行符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆