crzyonez777
crzyonez777

Reputation: 1807

how to write a regex to match a "\n" which is not followed another "\n"?

I want to replace "\n" with ""(empty string) only when "\n" is not followed by another "\n".

var text  = "abcdefg
             abcdefg

             1234556
             1234556

             ABCDEFG
             ABCDEFG";

So, if I have a string as the above, I want to make it like this after replacing "\n"s.

"abcdefgabcdefg

 12345561234556

 ABCDEFGABCDEFG";

But, I can't find out how to write a regex to match a "\n" that is not followed another "\n".

These are what I tried, but these match both "\n" and "\n\n".

var pattern1 = new RegExp("\\n{1}");
var pattern2 = new RegExp("\\n(?!\\n)");

Could anyone please help me to write a regex in this case?

Thanks!

Upvotes: 0

Views: 69

Answers (3)

Rag
Rag

Reputation: 6593

You can use negative lookahead to match \n which aren't followed by another \n:

\n(?!\n)

Upvotes: 0

h2ooooooo
h2ooooooo

Reputation: 39532

You can use /([^\n])\n([^\n])/g and replace it with \1\2.

Usage:

> str = 'abcdefg\nabcdefg\n\n1234556\n1234556\n\nABCDEFG\nABCDEFG';
> str.replace(/([^\n])\n([^\n])/g, '\1\2');
  "abcdefbcdefg

  123455234556

  ABCDEFBCDEFG"

REGEX DEMO

FIDDLE

Upvotes: 1

sshashank124
sshashank124

Reputation: 32189

You can match the following:

[^\\n](\\n)[^\\n]

Demo: http://regex101.com/r/eP9xD1

Upvotes: 4

Related Questions