[英]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);
g
modifier to replace all occurrences g
修饰符替换所有出现的事件 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.