2

For instance, I have a sourceString : 1234\n\n\n\n5678

and, I want to replace the first 2 \n within a \n sequence that must be equal to or more than 2 characters

so, the result I expect goes : 1234TEST\n\n5678

I tried : (^|[^\n])\n{2}

and the actual result is: 123TEST\n\n5678

http://regex101.com/r/cS6uG3

What's wrong with my code?

The basic idea is from @Tim Pietzcker 's tutorial on my previous question.

Thanks.

Regex to match single new line. Regex to match double new line

Community
  • 1
  • 1
  • So you want to replace the first two `\n` characters even if there are only two? E.g., `1234\n\n5678` becomes `1234TEST5678`? – matts Aug 02 '13 at 14:19

2 Answers2

1

This positive lookahead based regex should work:

var repl = "1234\n\n\n\n5678".replace(/\n{2}(?=\n{2,})/, "TEST");

/\n(?=\n{2,})/ means match \n\n if it is immediately followed by 2 or more \n

anubhava
  • 761,203
  • 64
  • 569
  • 643
0

What is happening here is that:

(^|[^\n])\n{2}
^-------^ -- this part

matches 4 and it's replaced. You need to included it again in your replacement.

var string = "1234\n\n\n\n5678";
string.replace(/(^|[^\n])\n{2}/g, "$1TEST");
                                   ^^-- back-reference
Halcyon
  • 57,230
  • 10
  • 89
  • 128
  • Thanks, Frits. Your answer is really clear. Along with my previous post, I understand. –  Aug 02 '13 at 14:21