i have an array of strings like below,
const arr = [
"list-domain/1/",
"list-domain/1/list/1",
"some-group/2/",
"some-group/2/list/2",
"list/3/",
"list/3/item/1"
];
as seen from above array i want to check if the array contains strings of kind
"list-domain/1/" or "some-group/2/" or "list/3/"
here the numbers after / can be anything. meaning in "list-domain/1" here 1 can be 2 or 3 anynumber i have to check if the string contains list-domain or some-group or list followed by / and any number followed by /
so for the above array the expected output is true.
now consider array below,
const arr1 = [
"list-domain/1/list/1",
"some-group/2/list/2",
"list/3/item/1"
];
for arr1 the expected output is false althought there is strings list-domain/1, some-group/2 and list/3 but they are followed by someother strings too like list-domain/1/list/1, some-group/2/list/2, list/3/item/1
so i want to find the exact strings numbers can be anything after /. could someone help me how to do this. thanks.
EDIT:
i want it to return true if the string has "list/1/" or
any string followed by "list/1" but return false if "list/1" is followed by someother string like below
"list-domain/1/list/1/item/1"
true in cases below
"list-domain/1/list/1"
"list/2"
"some-group/3/list/3"
Use a regular expression. Here is an example.
const rx = /^(([^\/]+)\/(\d+)\/)+$/
// or without the groups
const rxNoGroups = /^([^\/]+\/\d+\/)+$/
const found = items.filter(it => rx.test(it))
This regex tests
Tailor it to your needs. I coded it so your non-number words can still contain numbers, so foo/2/bar3/4/. You can also limit number of repetitions.
You can also just test that the string ends with /.
This gives you the required output using Regular Expression (RegExp):
arr.some(a=> new RegExp(/^(list-domain|some-group|list)\/[0-9]+\/$/g).test(a))
If you can count on the shape of pattern being always a string identifier followed by a numerical id a parser might look as follows:
const arr = [
"list-domain/1/",
"list-domain/1/list/1",
"some-group/2/",
"some-group/2/list/2",
"list/3/",
"list/3/item/1"
];
const parse = (str) => {
const parts = str.split('/');
return parts.reduce((parsed, part, i, parts) => {
if (part === '') return parsed;
if (i % 2 === 0) {
parsed[part] = null;
} else {
parsed[parts[i-1]] = part;
}
return parsed;
}, {});
}
arr.forEach(s => {
console.log(parse(s));
})
// returns:
// {list-domain: "1"}
// {list-domain: "1", list: "1"}
// {some-group: "2"}
// {some-group: "2", list: "2"}
// {list: "3"}
// {list: "3", item: "1"}
It returns an object where keys are the string identifiers and values numerical ids. However, as I said, it relies on the exact shape of the string and regular alteration of an identifier and a value.