regex for date in javascript -


this question has answer here:

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

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

but doesnt:

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

you have typo may not know why. second expression looking d{4} rather \d{4}. without backslash, you're looking letter d rather number.

additionally, {2} means you're looking 2 of preceding character/group, 1/1/2014 won't test positive. {1,2} match 1 to 2 consecutive items. first expression achieves functionality \d\d?. ? matches whether or not 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));  });

see mdn's regular expressions documentation, particularly explanations \d, ?, , {n,m}.


Comments

Popular posts from this blog

Payment information shows nothing in one page checkout page magento -

tcpdump - How to check if server received packet (acknowledged) -