I have a problem with my code. I have a series of string. For example I made this:
var a = 12345678
I want to split these string into an array, so that it will produce something like this:
[12,23,34,45,56,67,78]
I already tried this code:
var newNum = a.toString().match(/.{1,2}/g)
and it returns this result instead of the result I wanted
[12,34,56,78]
Are there any solution to this? Thanks in advance.
Shortest way:
'abcdefg'.split(/(..)/g).filter(s => s);
// Array(4) [ "ab", "cd", "ef", "g" ]
Explanation: split(/(..)/g) splits the string every two characters (kinda), from what I understand the captured group of any two characters (..) acts as a lookahead here (for reasons unbeknownst to me; if anyone has an explanation, contribution to this answer is welcome). This results in Array(7) [ "", "ab", "", "cd", "", "ef", "g" ] so all that's left to do is weed out the empty substrings with filter(s => s).
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