简体   繁体   中英

Javascript RegExp object adding characters

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.

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM