2

I have an array containing strings such as

/en/about
/fr/a-propos
/de/uber
/something-else

I want to test if a given string such as "/about" matches /en/about

more specifically I want to know if it matches "slash + exactly 2 lowercase alpha characters + /about"

I have this working like this:

const routes = [
    '/en/about',
    '/fr/a-propos',
    '/de/uber',
    '/something-else',
];

const regEx = /^(\/[a-z]{2}\b(\/about)\b)$/;

Object.keys(routes).forEach((k) => {
    if (regEx.test(routes[k])) {
        console.log(`redirecting /about to ${routes[k]}`);
    }
});

Now.. very simply.. I want to use a variable instead of hardcoding "/about". I need to put "/about" in a variable and use that to test. I know I'm supposed to use a RegExp to accomplish this, but I've been trying for half an hour and can't figure out how to convert the above regex into one that will work with RegExp and a variable

Appreciate the help!

vesperknight
  • 720
  • 9
  • 17

1 Answers1

1

You may use it like this code:

const routes = [
    '/en/about',
    '/fr/a-propos',
    '/de/uber',
    '/something-else',
];

const suffix = '/about';
const regEx = new RegExp(`^/[a-z]{2}${suffix}$`);

routes.forEach(k => {
    if (regEx.test(k)) {
        console.log(`redirecting /about to ${k}`);
    }
});
  • You need RegExp object creation
  • You may also simplify your forEach loop iteration
  • There is no need to use a word boundary after ^ or / and before $ or / because / is not a word character and anchors are also boundary matchers.
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
anubhava
  • 761,203
  • 64
  • 569
  • 643