Reputation: 428
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");
}
Upvotes: 0
Views: 59
Reputation: 521289
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
.
Upvotes: 2