-2

I am trying to write the RegExp that begins with either the space or the word, but I want to pass the word using the variable. Does anyone have idea about this?

  • Did you try [How do you use a variable in a regular expression?](https://stackoverflow.com/questions/494035/how-do-you-use-a-variable-in-a-regular-expression?rq=1)? – ggorlen Dec 13 '22 at 04:52

1 Answers1

1

Regex express is just a normal string, you can replace the variable with string method and then use it as pattern. For example:

const getPattern = function (placeholder) {
  return new RegExp(`\\s*${placeholder}\\s*$`);
}
const matcher = getPattern('firstName');
console.log(matcher.exec('my firstName '));