Regexp Solution
The proper regex matching all of your dates is: \d{1,2}/\d{1,2}/\d{4}
. Notation
{n,m}
is called limiting repetition and in this case \d{n,m}
means "between n and m digits (inclusive)". You can read more about that here: Limiting Repetition.
If you want to create matching groups, use "(" and ")" (parentheses). Addiitonally, in JavaScript, you have to to escape /
with \
and thus your regexp is: /(\d{1,2})\/(\d{1,2})\/(\d{4})/
You can use exec
function of the regexp to match strings against it. It returns an array containing the matched text as the first element and then one item for each of the matched groups.
You can find out more on MDN RegExp.prototype.exec or see this example below:
const datePattern = /(\d{1,2})\/(\d{1,2})\/(\d{4})/;
const date = datePattern.exec("11/12/2014"); // ["11/12/2014", "11", "12", "2014"]
Note: If an invalid string is passed (not matching the regular expression) exec
function will return null
. It's an easy way to do brief validation of users' input or data.
Alternative solution
Alternatively you can simply split the strings:
"11/12/2014".split('/'); // ["11", "12", "2014"]
But this will work regardless of what the string actually contains (it might contain string "ba/tm/an"
and split will still return an array with three elements). For this reason, Regexp is probably a better fit if you want to validate the dates.