4

The eval seems to not understand the RegEx at all.

I got this string to Check for entered YEAR in the input field.

The RegEx should match something like: 2010, 1980 or any Year between 1900 to 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

Please see fiddle: http://jsfiddle.net/zq30puzm/

This is being used in:

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

It keeps on printing the Error event when the input data is a deserving one.

What could be the issue?

Any suggestion is appreciated.

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

3
  • 3
    BTW: eval is evil. eval("/.../") is functionally equivalent to new Regexp("..."), but much slower and less safe. Almost everything in JavaScript can be done without eval - and should be. Commented Aug 21, 2014 at 15:56
  • Great Advice: can you tell how to do that with new RegExp? I tried; var str=new RegExp("/^(19|20)\d{2}$/"); str.test(2013) //logs false. How best to do it using new RegExp()?? Commented Aug 21, 2014 at 16:27
  • Same answer as Jake King's: with new Regexp you're using a string literal as a parameter, and in a string literal backslashes need to be escaped. Commented Aug 22, 2014 at 16:40

1 Answer 1

14

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

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

In regular expression literals, escaping backslashes is unnecessary (unless you need a literal backslash), but in a string, \d simply becomes the character d without escaping.


As a note of caution, eval should really be avoided at all costs. It's highly unlikely that you ever need it, and using it can always be dangerous without ample care to ensure that it can't be abused for malicious purposes. Furthermore, if your regex is malformed or some other error occurs, you won't get a helpful error message, it will likely just break in strange ways.

If you can, use RegExp literals! They are convenient and reliable, and you don't have to do any unnecessary escaping:

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

If you need the regex from a string, use the constructor instead of eval. It will do the same thing, but more safely.

new RegExp("^(19|20)\\d{2}$").test(2013);
Sign up to request clarification or add additional context in comments.

1 Comment

One small issue - RegExp literals can still require escaping e.g. var result = "thing".match(/^\/\//) vs eval('var result = "thing".match(/^\/\//)')

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.