0

I have a date like this: "2019" and i want to find a regex for it in javascript. my code return false at all. can you help me please ?

let regex = new RegExp('\d{4}');
if regex.test("2019"){
    console.log("true");
} else {
    console.log("false");
}

1 Answer 1

2

The immediate error in your syntax is that your are using RegExp, in which you would need to double escape \\d{4} your pattern. So new RegExp('\\d{4}') should work.

Your regex logic seems OK, but I would recommend that you always use the native regex syntax if possible:

var input = "2019";
if (/^\d{4}$/.test(input)) {
    console.log("true");
}
else {
    console.log("false");
}

An exception for using RegExp with its string constructor would be a situation where you had to build a regex pattern by piecing together other strings. In this case, you might have to use RegExp.

Sign up to request clarification or add additional context in comments.

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.