Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript eval cannot understand some RegEx in string?

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/

like image 887
ErickBest Avatar asked Oct 21 '25 05:10

ErickBest


1 Answers

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);
like image 184
Alexis King Avatar answered Oct 23 '25 18:10

Alexis King



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!