본문 바로가기
개발 지식

[Regex] g flag 사용 시 regex test can not use twice?

by PrettyLog 2023. 3. 31.

JavaScript RegExp cant use twice? [duplicate]

 

JavaScript RegExp cant use twice?

I have a very strage problem: var cat = [ { slug: "test/foo", id: 1}, { slug: "test/bar", id: 1}]; var searchreg = new RegExp("test","g"); cat.forEach(function(item){ if(searchreg.test(item.slu...

stackoverflow.com

글로벌 g 플래그 사용 시 첫 번째 매치를 찾은 곳을 기억 후 다음 test 실행 시 그 위치부터 찾기 시작한다. 한 문장에서 같은 단어를 여러번 찾는게 아니라면 g 플래그를 사용하지 말자

 

 

Because of g flag can not use test twice

Search:: regex test how does it work when test twice

It's because of the g ("global") flag.

RegExp instances have state when you use the g flag: They remember where the last match they saw was, so they can continue from that point (for instance, if you're using them in a loop). (Yes, this is not the best design it could have had.) So the first time, it finds test in the string (and notes that it's not at the end of the string); the second time, it tries to find test continuing in the previous string from the previous location, and of course doesn't find it. The third time, since it knows it ran out of input last time, it looks at the input again.

In your case, since you don't need to search further than the first instance, simply remove the g flag:

var searchreg = /test/; // That's a regex literal, basically: ... = new RegEx("test")

Alternately, you could reset it by assigning 0 to its lastIndex property:

searchreg.lastIndex = 0;
if (searchreg.test(item.slug))

Or, in this specific use case, you don't need regex at all:

if (item.slug.indexOf("test") !== -1) {
    // It has "test" in the slug
}

댓글