Is it possible to split a string (possibly with regex) so that every other number is a pair(starting from the right hand end)?
// 1 [1]
// 12 [12]
// 123 [1,23]
// 1234 [1,2,34]
// 12345 [12,3,45]
// 123456 [1,23,4,56]
// 1234567 [1,2,34,5,67]
// 12345678 [12,3,45,6,78]
// 123456789 [1,23,4,56,7,89]
// 1234567890 [1,2,34,5,67,8,90]
I tried reversing the string & then adding blocks of alternating two and one characters till the end (front) of the string. Then reversing it again. That mainly worked but it was flawed (didn't work for all cases). I also tried the regex
(\d\d)(\d)(\d\d)(\d)(\d\d)(\d)
But that doesn't work either (only in the regex tester ironically) - it's too long but I'll need it to work for 10 digit numbers max.
No so hard:
Start from the right, I will take one time 2 digits, the second time 1 digits.
Using slice. Then I will use unshift to push it in the begining of the array.
I'm using a flag, to know when to take only 1 parameter, and when to take two parameters (pair flag)
m(1)
m(12)
m(123)
m(1234)
m(12345)
m(123456)
m(12345678)
m(123456789)
m(1234567890)
function m(x){
x=x.toString()
var a=[]
var v;
var y=2
while(x){
v=x.slice(-y)
x=x.slice(0,-y)
y=y==1? 2:1
a.unshift(v)
}
console.log(a)
}
Result:
["1"]
["12"]
["1", "23"]
["1", "2", "34"]
["12", "3", "45"]
["1", "23", "4", "56"]
["12", "3", "45", "6", "78"]
["1", "23", "4", "56", "7", "89"]
["1", "2", "34", "5", "67", "8", "90"]
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