bdanger bdanger - 7 months ago 11
Javascript Question

regex for date in javascript

how come when searching for dd/mm/yyyy in a string
this works:

/(\d\d?)\/(\d\d?)\/(\d{4})/


but this doesnt:

/\d{2}\/\d{2}\/d{4}/

Answer

You have a typo but you may not know why. Your second expression is looking for d{4} rather than \d{4}. Without that backslash, you're simply looking for the letter d rather than a number.

Additionally, the {2} means that you're looking for exactly 2 of the preceding character/group, so 1/1/2014 won't test positive. {1,2} will match one to two consecutive items. The first expression achieves that functionality with \d\d?. The ? matches whether or not the preceding character/group exists.

var tests = [
    { rx: /\d{2}\/\d{2}\/d{4}/, text: "10/10/dddd" },    // true
    { rx: /\d{2}\/\d{2}\/\d{4}/, text: "10/10/2014" },   // true
    { rx: /\d{2}\/\d{2}\/d{4}/, text: "1/1/2014" },      // false
    { rx: /\d{1,2}\/\d{1,2}\/\d{4}/, text: "1/1/2014" }, // true
    { rx: /\d{1,2}/, text: "0" },                        // true
    { rx: /\d{1,2}/, text: "00" },                       // true
    { rx: /\d\d?/, text: "0" },                          // true
    { rx: /\d\d?/, text: "00" },                         // true
];

tests.forEach(function(t){
    console.log("rx: %s, text: %o, matches: %o", t.rx, t.text, t.rx.test(t.text));
});
<!-- console visualization; see http://meta.stackexchange.com/a/242491 -->
<script src="http://gh-canon.github.io/stack-snippet-console/console.min.js"></script>

See MDN's Regular Expressions documentation, particularly the explanations for \d, ?, and {n,m}.

Comments