简体   繁体   English

使用Javascript替换文本中的多个空白行

[英]Replace multiple blank lines in text using Javascript

Hopefully a simple question. 希望是一个简单的问题。

If I have text like this: 如果我有这样的文字:

Orange
Apples


Melons

Bananas

...how can I replace all occurrences of multiple blank lines with single blank lines, ending up with this: ...我如何用单个空白行替换所有出现的多个空白行,最后是这样:

Orange
Apples

Melons

Bananas

Fiddle: http://jsfiddle.net/Jq4pT/ Need to remove multiple blank lines from the first box's input before inserting into the second. 小提琴: http : //jsfiddle.net/Jq4pT/在插入第二个框之前,需要从第一个框的输入中删除多个空白行。

I've found this link , but am not sure how to use that regular expression in Javascript? 我找到了此链接 ,但不确定如何在Javascript中使用该正则表达式?

Thanks. 谢谢。

Just use it like this: 像这样使用它:

var inputString = '...';
var outputString = inputString.replace(/^(\s*\r\n){2,}/, "\r\n")

This is an old question, but I don't care, it comes up first in Google search. 这是一个古老的问题,但我不在乎,它首先出现在Google搜索中。

You can do this with the following code: 您可以使用以下代码执行此操作:

var EOL = string.match(/\r\n/gm)?"\r\n":"\n";
var regExp = new RegExp("("+EOL+"){3,}", "gm");
string = string.replace(regExp, EOL+EOL);
  • First it determines the endline char to use in Regex 首先,它确定要在Regex中使用的终端字符
  • Regex looks for EOL chars being repeated 3 or more times, and replaces them with 2 EOL chars. 正则表达式查找重复3次或更多次的EOL字符,并用2个EOL字符替换它们。
  • Using g modifier to replace all occurrences 使用g修饰符替换所有出现的事件
  • Using m modifier to apply regex to the whole multi-line string, instead of per line. 使用m修饰符将正则表达式应用于整个多行字符串,而不是每行。

Using simple regular expressions: 使用简单的正则表达式:

str = "whatever your string is";
reg = /\n\n\n/;
str.replace(reg, "\n\n");

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

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