6

I'm trying to validate only 4 numbers like this:

Regex

It is working on the above page, but when I use it on a script it is not working:

var reg = new RegExp('^\d{4}$/');
reg.test(1234);
reg.test('1234');

Both are returning false...

If I test on the browser console like this:

/^\d{4}$/.test('1234');
/^\d{4}$/.test(1234);

Both are returning true.

What I'm missing?

8
  • 1
    You could simply use /^\d{4}$/.test(1234) directly in your code ? Commented Nov 8, 2017 at 16:14
  • 1
    And if you still need the variable you should initialize it like this var reg = RegExp(/^\d{4}$/) Commented Nov 8, 2017 at 16:14
  • 1
    looks like you're missing a single slash '^\d{4}$/' should be '/^\d{4}$/' Commented Nov 8, 2017 at 16:15
  • 1
    You're using different code in your script vs. the console. That's why you're getting different results. Commented Nov 8, 2017 at 16:17
  • 1
    @RobbieMilejczak - close . . . you don't use the opening and closing slashes in a string parameter for the RegExp constructor. Also the \d needs to have its slash escaped in a RegExp string parameter (i.e., \\d). Basically, Chin Leung nailed it in his answer below. :) Commented Nov 8, 2017 at 16:19

1 Answer 1

13

The problem is because your RegExp is not initialized properly.

You can either do:

// Note the \\ to escape the backslash
var reg = new RegExp('^\\d{4}$');

Or

var reg = new RegExp(/^\d{4}$/);
Sign up to request clarification or add additional context in comments.

1 Comment

this helped me, can't reuse it each time apparently

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.