If I understand your problem correctly in a more general sense, it is to find whether a path is nested in another path (is a subtree). This IMO would be the right way to approach it as you don't want your solution to be specific to the url strings provided, as they can change in the future.
Proposed solutions:
Non-regex solution: Ensure url1 starts with given base url (url2) and check if after splitting on '/' the number of sub paths of url1 is greater than those of base url.
const isNested = (url1, url2) => {
return url1.indexOf(url2) === 0 &&
url1.split("/").length > url2.split("/").length
}
> isNested('a/b/c', 'a/b')
true
> isNested('a/b/cd', 'a/b')
true
> isNested('x/b/cd', 'a/b')
false
> isNested('a/b/cd', 'x/a/b')
false
> isNested('a/b/cd/z', 'x/a/b')
false
> isNested('a/b/cd/z', 'a/b')
true
we can add a depth parameter to test for specific depth
const isNested = (url1, url2, depth) => {
url1.indexOf(url2) === 0 && depth
? url1.split("/").length - url2.split("/").length === depth
: url1.split("/").length > url2.split("/").length
}
> isNested('a/b/cd/z', 'a/b')
true
> isNested('a/b/cd/z', 'a/b', 1)
false
> isNested('a/b/cd/z', 'a/b', 2)
true
Regex solution: Not recommended as it is difficult to read and modify.
const isNested = (url1, url2) => {
let escaped = url2.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&")
let regex = new RegExp(`(^${escaped})(\/[\/a-zA-Z0-9_-]+)`, "gm")
return url1.match(regex) ? true : false
}
> isNested('a/b/c/d', 'a/b/c')
true
> isNested('a/b/c', 'a/b/c')
false
> isNested('a/b/c/de', 'a/b/c')
true
> isNested('a/b/c/de/fg', 'a/b/c')
true
> isNested('x/a/b/c/de/fg', 'a/b/c')
false
/dominName\/profilePics\/.*$/i.test(url2)