I've created the example below to illustrate what I'm trying to do. Essentially I wanted to get the array index of the true match and return a custom response based on which end point regex was matched.
Is this possible with array some()
? Or is there a different method?
// Simulate an http request
const reqUrl = "http://127.0.0.1/app/api/v1/customers/999999";
// Parse the parts of a url
const url = new URL(reqUrl);
// Get url pathname and Decode it, if encoded
const urlPathNameDecoded = decodeURIComponent(url.pathname);
/* /app/api/v1/customers/999999 */
console.log(urlPathNameDecoded);
// Create list of regular expressions to match against url pathname decoded
const regexList = [
/apple/,
/^\/app\/api\/v1\/customers\/([1-9]{1}[0-9]{0,8})\/?$/, // Match -> /app/api/v1/customers/999999
/orange/,
/^\/app\/api\/v1\/projects\/([1-9]{1}[0-9]{0,8})\/?$/, // Match -> /app/api/v1/projects/999999
/pear/,
/^\/app\/api\/v1\/vendors\/([1-9]{1}[0-9]{0,8})\/?$/, // Match -> /app/api/v1/vendors/999999
/strawberry/,
];
// Test if at least one element in the array passes the test implemented by the provided function
const isMatch = regexList.some(regex => regex.exec(urlPathNameDecoded));
console.log("isMatch:", isMatch);