Good day,
I am trying to return groups of 3 digits of a given string where digits are "consumed" twice in JavaScript:
From a string "123 456" I would like exec to return ["1", "12"] for the first match, ["2", "23"] and so on.
I tried using a lookahead like this:
let exp = /(\d(?=\d\d))/g;
let match;
while(match = exp.exec("1234 454")) {
console.log(match);
}
This, will however still only each digit which precedes two digits.
Does someone have a solution? I have searched but am not exactly sure what to search for so I might have missed something.
Thank you in advance!
You need to capture inside a positive lookahead here:
let exp = /(?=((\d)\d))/g;
let match;
while(match = exp.exec("1234 454")) {
if (match.index === exp.lastIndex) { // \
exp.lastIndex++; // - Prevent infinite loop
} // /
console.log([match[1], match[2]]); // Print the output
}
The (?=((\d)\d)) pattern matches a location followed with 2 digits (captured into Group 1) the first being captured into Group 2.
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