1

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 e.g.

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.

4
  • 2
    You are replacing every occurrence of one \n with one \n Commented Jan 4, 2016 at 17:37
  • Your goal is very unclear, and the fact you misuse the code snippet feature (it's supposed to help test your code) doesn't help Commented Jan 4, 2016 at 17:38
  • 1
    var str=inputList.replace(/\n+/gm,"\n"); ???? I am confused with the final output... So if there is only one, than you replace it with no line breaks? Commented Jan 4, 2016 at 17:39
  • Try var str=inputList.replace(/\n{2,}/g,"\n");. If that does not work, try also var str=inputList.replace(/(\r?\n|<br\s*\/?>){2,}/g,"\n");. Commented Jan 4, 2016 at 17:42

3 Answers 3

3

(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

Sign up to request clarification or add additional context in comments.

2 Comments

There is no need escaping \n as \\n and the capturing group is redundant here. And /m modifier is also redundant.
so what do you suggest? /\n{2,}/gm also seems to work, if that's what you mean
0

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");
                             ^^^^

Comments

0

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

Instead do:

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

3 Comments

I believe OP is trying to replace TWO \n or more with one \n.
Why use /m modifier?
@JeremyThille I believe we should wait to have a proper question before to guess the need

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.