✘✘✘ Web
[Javascript][Regex] Regex test does not select all items from a list
PrettyLog
2022. 8. 22. 12:04
[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"]