Hi below is an array of strings,
const arr = [
"list-domain/1/",
"list-domain/1/list/1",
"some-group/2/",
"some-group/2/list/2",
"list/3/",
"list/3/item/1"
];
I want to return true if the string matches "list/1/"
or "list-domain/2/list/2/"
or "some-group/3/list/4"
; so basically should return true if string starts with "list/1/"
or has some string in front and ends with "/list/1/"
note: here the number after slash can be any number.
so for the above array expected output is true.
const arr1 = [
"list-domain/1/",
"list-domain/1/list/1",
"some-group/2/",
"some-group/2/list/2",
];
for arr1 expected output true
const arr2 = [
"list-domain/1/",
"list-domain/1/list/1/item/2",
"some-group/2/",
];
for arr2 expected output is false.
i have tried something like below,
const foundMatch = arr.some(a=> new RegExp(/(\/list\/[0-9] )?\/$/g).test(a));
but this doesn't work
CodePudding user response:
Try this:
arr.some(a=> new RegExp(/(^list\/\d\/)|(list\/\d\/$)/).test(a));
If that's what you mean by:
If string starts with "list/1/" or has some string in front and ends with "list/1/".
CodePudding user response:
Is this what you want to have?
arr.some(a=> new RegExp(/list\/[0-9](\/)?$/g).test(a));
Your above all cases fulfills by this regex. If not you can put other test cases.