I have a regex like the following:
const regex = /(\d{4})-(\d{2})-(\d{2}) (\d{2}):(\d{2}):(\d{2})/;
const result = "1988-02-01 12:12:12".match(regex);
console.log(result)
Here, the result is having the first item as a whole match, is it possible to exclude the whole match from the result in anyway? Currently I ended up doing a shift() on the result, just wondering if the whole match can me marked as non-capturing in anyway.
You can use destructuring to split-off the first value from the result array with [,...result]:
const regex = /(\d{4})-(\d{2})-(\d{2}) (\d{2}):(\d{2}):(\d{2})/;
const [,...result] = "1988-02-01 12:12:12".match(regex);
console.log(result)
If you know the input format is OK, then you can do:
result = "1988-02-01 12:12:12".match(/\d+/g)
const regex = /(\d{4})-(\d{2})-(\d{2}) (\d{2}):(\d{2}):(\d{2})/;
const result = "1988-02-01 12:12:12".match(/\d+/g);
console.log(result)
Or with a bit more checking: .match(/(^\d{4}|\b\d{2})\b/g)
const regex = /(\d{4})-(\d{2})-(\d{2}) (\d{2}):(\d{2}):(\d{2})/;
const result = "1988-02-01 12:12:12".match(/(^\d{4}|\b\d{2})\b/g);
console.log(result)
Additionally, if you want to have the array with the numeric data type equivalents, then map using Number as callback function:
const regex = /(\d{4})-(\d{2})-(\d{2}) (\d{2}):(\d{2}):(\d{2})/;
const [,...result] = ("1988-02-01 12:12:12".match(regex)||[]).map(Number);
console.log(result)
The additional ||[] treats the case where the pattern does not match, and exchanges the null with an empty array.
You can take a look at named groups
const regex = /((?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})) (?<hour>\d{2}):(?<minutes>\d{2}):(?<seconds>\d{2})/;
const result = "1988-02-01 12:12:12".match(regex).groups;
console.log(result)
console.log(Object.values(result))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With