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,504
  • 1
  • 14
  • 34

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
  • 26,396
  • 4
  • 55
  • 62
AmsalK
  • 416
  • 5
  • 9
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".