简体   繁体   中英

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 . 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)

If you are trying to replace two or more \\n with one, try this :

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

{2,} means 2 or more

You are replacing \\n with \\n in your code.

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. If you do not want to match just one use {2,} to match two or more.

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

or

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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