Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split String Every 2 Character into Array

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.

like image 815
Mohammad Iqbal Avatar asked Jan 02 '23 02:01

Mohammad Iqbal


1 Answers

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).

like image 169
Adam Jagosz Avatar answered Jan 13 '23 02:01

Adam Jagosz