javascript - Why does the regex stop working when constructed as a string? -
this question has answer here:
- why javascript regex doesn't work? 1 answer
- javascript regex not working 1 answer
- why regex constructors need double escaped? 4 answers
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
Post a Comment