I had a task to split a string by a two chars groups.
So '031745'
→ [03,17,45]
I took the regex approach and successfully managed to do it via:
'031745'.split(/(?=(?:..)+$)/);
// result: ["03", "17", "45"]
I'm aware of what's going on here: We are trying to split by invisible location which has subsequent groups of 2 chars, repeatedly.
But there are two things which I find hard to explain:
1.
If I remove the
end
char$
, I get this result:'031745'.split(/(?=(?:..)+)/); // result: ["0", "3", "1", "7", "45"]`
Why does removing
$
affects the result? After all, we're just looking for repeated - non-overlapped two chars.
2.
Why does changing the inner group to a non-captured-group, causing to yield a different result:
'031745'.split(/(?=(..)$)/); // result: ["0317", "45", "45"]
AFAIK - captured groups are for back reference and for capturing a group. After all - it's still a group of two chars being repeated, so what makes
(..)
behaves differently than(?:..)
in this particular case?
nb, I know there are other approaches but still I want to stay with Regex - learning purpose.