javascript - Why does the regex stop working when constructed as a string? -


i have regular expression works when constructed via native regex primitive:

var regex = /^(?:533-)?\d{3}-\d{4}$/; '533-123-4567'.match(regex) ["533-123-4567", index: 0, input: "533-123-4567"] 

but fails when constructed via string:

var regex = new regexp('/^(?:533-)?\d{3}-\d{4}$/'); '533-123-4567'.match(regex) null 

i have tried escaping slashes no avail. documentation on characters must escaped?

when use constructed new regexp () not need escape or enclosing (//) string. second regex may looks this:

var regex = new regexp('^(?:533-)?\\d{3}-\\d{4}$'); console.log('533-123-4567'.match(regex)); 

refer documentation here.

however, first regex need yo escape because not calling constructor , have precise javascript writing regex.


Comments

Popular posts from this blog

python - Operations inside variables -

Generic Map Parameter java -

arrays - What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it? -