[javascript] RegEx g flag <> test
flag: g >> remember lastIndex
/c/ig.test('ccc') // true
/c/ig.test('ccc') // false
// vs
/c/i.test('ccc') // true
/c/i.test('ccc') // true
Don’t use g if you want to test several times Or Before another test, you should make test return false
시나리오
Senario
I want to get all items that contains my search words. I used Regex test to filter a list.
const regex = new Regex("search", "ig");
const list = [
"abc",
"abd",
"a",
"b",
];
const filteredList = list.filter((s) => regex.test(s));
// I expect ["abc", "abd"], but I got ["abc"];
Problem
only got [”abc”]
Solution
You need to remove “g” from the flags
Don’t use g if you want to test several times Or Before another test, you should make test return false
const regex = new Regex("search", "i");
const list = [
"abc",
"abd",
"a",
"b",
];
const filteredList = list.filter((s) => regex.test(s)); // ["abc", "abd"]
'✘✘✘ Web' 카테고리의 다른 글
Editable Dom => attribute: contentEditable (0) | 2022.07.22 |
---|---|
Dom id => window[id] or document.querySelector('#id') (0) | 2022.07.22 |
the-dom-challenge: Build something with only vanilla Javascript (0) | 2022.07.22 |
[axios] onUploadProgress - progress bar (0) | 2022.07.07 |
[chrome][devtools] elements tab right click not working (0) | 2022.07.07 |
댓글