위치 지정
문자열을 다루자 보면 ‘~~으로 시작하는 문자열’, ‘__으로 끝나는 문자열’, ‘그 문자열의 처음’하는 식으로 생각하게 될 때가 아주 많습니다. 여기서 ~~, __을 정규식의 앵커anchor라고 부릅니다. 앵커에는 두 가지 종류가 있습니다. ^는 문자열의 맨 처음을 나타내고, $는 문자열의 마지막을 나타냅니다.
const input = "It was the best of times, it was the worst of times";
const beginning = input.match(/^\w+/g); // It
const end = input.match(/\w+$/g); // times
const everything = input.match(/^.*$/g); // It was the best of times, it was the worst of times (input과 동일합니다)
const nomatch1 = input.match(/^best/ig); // null
const nomatch2 = input.match(/worst$/ig); // null
그런데 앵커에는 특이한 기능이 있습니다. 문자열에 줄바꿈 문자가 들어있다면 각 줄의 처음과 끝을 찾을 수 있습니다. 각 줄의 처음과 끝을 찾으면 m 플래그를 쓰면 됩니다.
const input = "On line\nTwo lines\nThree Lines\nFour";
const beginnings = input.match(/^\w+/mg); // On,Two,Three,Four
const endings = input.match(/\w+$/mg); // line,lines,Lines,Four