-1

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

Luan Nico
  • 5,376
  • 2
  • 30
  • 60
stackuser
  • 374
  • 2
  • 9
  • 1
    Remove the `?`. The constructor is useless, use a literal pattern.The parenthesis are useless too. If you want to allow `list` at the start of the string, change the first `\/` to `(?:\/|^)` – Casimir et Hippolyte Feb 04 '22 at 11:58
  • thanks so should it be arr.some(a => /(?:\/|^)list\/[0-9]+)?\/$/g.test(a)); – stackuser Feb 04 '22 at 12:08
  • you can use this website (https://rubular.com/) to test your regexes against samples and see what is wrong – Luan Nico Feb 04 '22 at 12:09
  • 1
    Does this answer your question? [How to match particular strings in an array using javascript?](https://stackoverflow.com/questions/70985007/how-to-match-particular-strings-in-an-array-using-javascript) – RaiBnod Feb 04 '22 at 12:15

2 Answers2

1

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/".

Henryc17
  • 851
  • 4
  • 16
0

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.

RaiBnod
  • 2,141
  • 2
  • 19
  • 25