Reputation: 7269
I'm trying to evaluate a test string against a regular expression I build from a string extracted from a hidden input element, the code is as follows
HTML
<input type="hidden" name="reg_2" id="reg_2" value="^\\d{5}$">
JS
var regTest = new RegExp( $('#reg_2').val(), 'g' );
var valid = "12345";
var invalid = "47";
alert(regTest.test(valid));<--Returns false
It keeps evaluating to false, I'm not sure if the syntax is wrong or if there's something else I'm missing. I tried with and without the global flag, and I also confirmed that the jQuery selector is returning the correct value. Any help or insight is welcome. Thank you.
UPDATE
Thank you for the prompt responses. I was following the example on the Mozilla Dev Network which shows a hardcoded string in the RegEx constructor with a double backslash and thought that's what I needed to pass to my script. Thanks again.
Upvotes: 1
Views: 2366
Reputation: 23132
You don't need to escape the backslash. The value of the hidden input should just be "^\d{5}$"
. Here's a working example.
Upvotes: 1
Reputation: 4077
Remove one slash in the input value:
<input type="hidden" name="reg_2" id="reg_2" value="^\d{5}$">
Upvotes: 2