3 ms·
I've used this for regexp's... const parse = /(\w+):(\d+)/.exec(str) if (parse) { const [, key, value] = match } (Where the elided first e
by jakear 4y ago
I've used this for regexp's...
const parse = /(\w+):(\d+)/.exec(str)
if (parse) {
const [, key, value] = match
}
(Where the elided first entry is the original string)
I've also had bugs where I forgot the leading comma and had all the wrong captures. Depending on the situation, I might instead recommend named captures:
const parse = /(?<key>\w+):(?<value>\d+)/.exec(str)
if (parse) {
const {key, value} = parse.groups
}
Caveat is it takes a bit to convince TS this is sound, and you have to manually sync the names. (https://github.com/microsoft/TypeScript/issues/32098 https://github.com/microsoft/TypeScript/issues/32098 would help)