0

I have a regex string that is getting passed into to my code, when I try to inject it into the RegExp object constructor, the RegExp object appears to be adding characters.

original string regex:

    /^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$/

After calling new RegExp(mystring); results in the following:

regex:

    /\/^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$\//

I can't hardcode the string in my js file, so I need a way to make this work.

0

1 Answer 1

2

You don't need to add the regex delimiters. And you must need to escape the backslash one more time, because single backslash inside double quotes would be treated as an escape sequence.

var re = "^\\(?([0-9]{3})\\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$";
var reg = RegExp(re);
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, I wasn't using double quotes, but the delimiters did the trick!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.