Home > Software engineering >  Getting RegExp source without "beforhand" and "afterward" patterns
Getting RegExp source without "beforhand" and "afterward" patterns

Time:01-07

I have such a constant object:

export const Roles = {
  match: {
    Applicant: /^applicant$/,
    Employee: /^employee$/,
    Default: /^default-roles/,
  },
  value: {
    Applicant: 'applicant',
    Employee: 'employee',
  },
};

I want to be able to get rid of Roles#match and Roles#value keys to be simply like:

export const Roles = {
    Applicant: /^applicant$/,
    Employee: /^employee$/,
    Default: /^default-roles/,
};

so I found RegExp.source. It does remove / but not other flags like ^ and $

CodePudding user response:

Do so using the replace method:

const source = Roles.Applicant.source;
const cleanedSource = source.replace(/^\^|\$$/g, '');
console.log(cleanedSource);  // prints "applicant"

Then, you could use the RegExp constructor to create a new regular expression object directly from the source property, like this:

const cleanedRegex = new RegExp(Roles.Applicant.source, Roles.Applicant.flags);
  • Related