So, for enabling the multiline mode the m flag is used.
The value of the multiline property is boolean: when the m flag is used, it’s true, otherwise- false. The m flag specifies that a multiline input string should be dealt with as multiple lines.
In the multiline mode, the anchors ^ and $ match not only at the start and the end of the string, but also at the beginning/end of the line.
Searching at Line Start ^¶
Now, let’s observe an example of using multiple lines. The pattern /^\d/gm takes a digit from the start of every line, like this:
let str = `1st: Javascrip 2nd: Css 3rd: Html`; console.log(str.match(/^\d/gm)); // 1, 2, 3
Only the first digit will be matched without using the m flag, as shown below:
The reason is that the ^ caret only matches at the start of the text, and within the multiline mode- at the beginning of any line.
Searching at Line End $¶
Now, let’s see how the dollar sign $ behaves.
The regexp \d$ can find the last digit in each line, like this:
Without using the m flag, the dollar sign $ could only match at the end of the text. Hence, only the last digit would be found.
Searching for \n Instead of ^ $¶
For finding a newline, you can use not only the anchors ^ and $ but the newline character \n, as well.
To reveal the difference, let’s consider an example where the search is for \d\n instead of \d$:
So, in the example above, instead of three matches, there are two.
The reason is that no newline exists after 3. The next difference is that now each match includes a newline character \n. In contrast to the anchors ^ $ (they only test the condition beginning/end of a line) \n is a character. Therefore, it is part of the result.
As a conclusion, let’s note that in the pattern, \n is used when it’s necessary to have newline characters in the result. The anchors, on their turn, are used for finding something at the start/end of a line.