Skip to main content

How to rewrite regexp in order to be able set variables inside?

I have following regexp for phone mask, but how pass variables inside. I read that we can use new Regexp constructor for this, but how actually it should work?

Example:

const maskPhone = (value: string, code) => {

  return value
    .replace(/(?<!^)\+|[^\d+]+/g, '')
    .replace(/(\d{2})(\d)/, '($1) $2') // how I can code here like this \d{code}
    .replace(/(\d{4})(\d)/, '$1-$2')
    .replace(/(-\d{3})(\d+?)$/, '$1-$2')
    .replace(/(-\d{3})(\d+?)$/, '$1-$2')
    .replace(/(-\d{3})(\d+?)$/, '$1')
}
Via Active questions tagged javascript - Stack Overflow https://ift.tt/kKRYGa3

Comments