IT/JavaScript

javascript 정규식에서 global flag 사용하면 정규식 객체가 lastIndex를 유지

underbell 2014. 11. 26. 10:20

javascript 정규식에서 global flag 사용하면 정규식 객체가 lastIndex를 유지? 한다는걸 저만 몰랐나요? ^^;; 

http://stackoverflow.com/questions/6891545/javascript-regexp-test-returns-false-even-though-it-should-return-true


This is a common behavior that the the exec or test methods show when you deal with patterns that have the global g flag.

The RegExp object will keep track of the lastIndex where a match was found, and then on subsequent matches it will start from that lastIndex instead of starting from 0.

For example:

var re = /^a/g;
console.log(re.test("ab")); // true, lastIndex was 0
console.log(re.test("ab")); // false, lastIndex was 1

Remove the g flag from your pattern, since you are looking just for a single match (you are testing each line separately).