Home > Net >  Why does the javascript regex /^abc/g not count two on "abc\nabc\n" with match(re).lengt
Why does the javascript regex /^abc/g not count two on "abc\nabc\n" with match(re).lengt

Time:01-02

var a = "abc\nabc\n";
var re = /^abc/g;
console.log(a.match(re).length);

This only returns 1. Why not 2?

Background: Actually I want to look for /^[ \t\v]*abc/g, but for this question /^abc/g is fine.

I haven't written anything for quite some time, so sorry for the easy question.

CodePudding user response:

By default ^ matches the beginning of the string, not the beginning of a line. Use the m flag to make ^ and $ process lines instead of the whole string.

var a = "abc\nabc\n";
var re = /^abc/gm;
console.log(a.match(re).length);

  • Related