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

ubuntu - PHP script to find files of certain extensions in a directory, returns populated array when run in browser, but empty array when run from terminal -

php - How can i create a user dashboard -

javascript - How to detect toggling of the fullscreen-toolbar in jQuery Mobile? -