Javascript eval can't understand some RegEx in string?

eval

doesn't seem to understand at all RegEx

.

I got this one string

to validate what was entered YEAR

in the input field.

RegEx should match

be something like 2010 , 1980, or any year between 1900 and 2099 .

RegEx : ^(19|20)\d{2}$

works well in raw javascript

something like:

var testStr = /^(19|20)\d{2}$/.test(2013) //logs true

      

but testStr2 = eval("/^(19|20)\d{2}$/").test(2013) //logs false

See fiddle: http://jsfiddle.net/zq30puzm/

This is used in:

"getYear":{
                        "regex":"/^(19|20)\d{2}$/",
                        "alertText":"* Invalid Year"
},

      

It continues to print an Error event when the input is meritorious.

What could be the problem?

Any suggestion is appreciated.

Fiddle: http://jsfiddle.net/zq30puzm/

+3


source to share


1 answer


In the string version, you need to escape the backslash.

var testStr2 = eval("/^(19|20)\\d{2}$/").test(2013);

      

In regex literals, you don't need to escape backslashes (unless you want a literal backslash), but in a string it \d

just becomes a character d

without escaping.


As a caveat, eval

it should really be avoided at all costs. It is highly unlikely that you will ever need it, and using it can always be dangerous without sufficient care that it cannot be abused for malicious purposes. Also, if your regex is malformed or some other error occurs, you won't get a useful error message, it will probably just break in a weird way.



Use RegExp literals if you can! They are convenient and reliable, and you do not need to make unnecessary shoots:

/^(19|20)\d{2}$/.test(2013);

      

If you need a regular expression from a string, use the constructor instead eval

. It will do the same, but safer.

new RegExp("^(19|20)\\d{2}$").test(2013);

      

+11


source







All Articles