JavaScript RegExp cant use twice? [duplicate]
글로벌 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
}
'개발 지식' 카테고리의 다른 글
[javascript] iterable, iterator 뜻 정의 (0) | 2023.04.05 |
---|---|
[media] window screen orientation 감지해서 Landscape 보여주기 (0) | 2023.03.31 |
이진수<-> 십진수 소수 파트 => fractional part: Binary number <-> Decimal number (0) | 2023.03.26 |
npm ci vs npm i (0) | 2023.03.23 |
[디자인 패턴] Observer pattern (0) | 2023.03.05 |
댓글