티스토리 뷰

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).


'IT > JavaScript' 카테고리의 다른 글

Canvas Base64 Image data 회전  (0) 2017.01.04
ECMAScript 6: what’s next for JavaScript? (August 2014)  (0) 2014.09.02
JavaScript todomvc  (0) 2014.07.21
e-mail check 정규식  (0) 2014.07.21
배열 중복 체크  (0) 2014.07.21
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
TAG
more
«   2025/01   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
글 보관함