Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why does the javascript regex /^abc/g not count two on "abc\nabc\n" with match(re).length?

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading