1

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.

2 Answers 2

2

Remove one slash in the input value:

<input type="hidden" name="reg_2" id="reg_2" value="^\d{5}$">
Sign up to request clarification or add additional context in comments.

Comments

1

You don't need to escape the backslash. The value of the hidden input should just be "^\d{5}$". Here's a working example.

Comments

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.