1

It should be very simple, but I cannot figure out, how to match the beginning and the end of a multiline string. Say, I want to know, whether the string contains foo at the beginning of the first line.

str = "foo\nbar";
reg = /^foo/m;
console.log( reg.test( str ) ); // → true

But if I swap foo and bar, thus placing foo in the second line, the result will (though shouldn't) be the same:

str = "bar\nfoo";
reg = /^foo/m;
console.log( reg.test( str ) ); // → true

So, is there a way to catch the beginning and the end of a multiline string?

Eugene Barsky
  • 5,780
  • 3
  • 17
  • 40

2 Answers2

4

You are using the multiline mode flag "m". With that flag, you are not just matching at the start of the text, but at the start of the lines. So when you have the line break \n before foo, this is the start of a new line, which will match the start query ^foo.

Here is a link with some more info: https://javascript.info/regexp-multiline-mode

Solution: as was said in the comment section below by Jacob, just take out the multiline mode if you only wish to match the start of the string,

str = "bar\nfoo";
reg = /^foo/;
console.log( reg.test( str ) ); // → false
CRice
  • 29,968
  • 4
  • 57
  • 70
AmsalK
  • 416
  • 5
  • 9
  • 2
    It sounds to me like the `m` flag isn't needed at all. Just remove that, and `^` and `$` work correctly. – Jacob Sep 06 '18 at 21:49
  • @AmsaIK I understand why it matches. But what will be the solution to my question? – Eugene Barsky Sep 06 '18 at 21:51
  • So, taking away the multiline flag is the only solution. Very inconvenient... Anyway, thanks! – Eugene Barsky Sep 06 '18 at 21:58
  • 2
    It's not the only solution. You could use a negative [lookbehind](https://stackoverflow.com/a/50434875/3390419) `reg = /(?<!\n)^foo/m;`, depending on your environment. – Paolo Sep 06 '18 at 22:04
  • @UnbearableLightness If I'm not mistaken (can't check now), lookbehind isn't supported yet outside of chrome. – Eugene Barsky Sep 06 '18 at 22:28
  • That's correct, hence why I specified *depending on your environment*. – Paolo Sep 06 '18 at 22:32
0

In this specific case, you may not need to use complicated regex at all. If you are always certain that you want to check if the very beginning of the string is "foo", then check if str.slice(0,3) === "foo".