简体   繁体   English

用字符串+ JavaScript中的单行替换多行

[英]Replace multiline with single line in a string+Javascript

I am trying to replace all multiplines with single line in a string in javascript but none is working . 我正在尝试用javascript中的字符串中的单行替换所有multiplines,但是没有一个工作。 Below is my code : 下面是我的代码:

var str=inputList.replace(/\n/gm,"\n");

input eg 输入例如

abc,def <3 newlines>


xyz <1 newline>
opp

Expected output: 预期产量:

abc,def <1 newline>
xyz
opp

Actual output: 实际输出:

abc,def<3 newlines>


xyz<1 newline>
opp

Any help is appreciated. 任何帮助表示赞赏。

(Edit : simplified version thanks to stribizhev) (编辑:简化版本,感谢stribizhev)

If you are trying to replace two or more \\n with one, try this : 如果要用一个替换两个或多个\\n ,请尝试以下操作:

var str = inputList.replace(/\n{2,}/gm,"\n");

{2,} means 2 or more {2,}表示2个或更多

You are replacing \\n with \\n in your code. 要更换\\n\\n在你的代码。

Instead do: 而是:

var str = inputList.replace(/\n/gm, "");

You are matching just one and replacing it with one. 您只匹配一个,并用一个替换它。 I believe if you just add the + after the \\n to match one or more. 我相信,只要在\\n后面加上+即可匹配一个或多个。 If you do not want to match just one use {2,} to match two or more. 如果您不想只匹配一个,请使用{2,}来匹配两个或多个。

var str=inputList.replace(/\n+/g,"\n");
                             ^

or 要么

var str=inputList.replace(/\n{2,}/g,"\n");
                             ^^^^

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

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