2

I have a string like

var str = "aabbrdfc0912";

and i want to convert it in an array in pair of two like

var arr = ["aa","bb","rd","fc","09","12"]; 

Please suggest.

Abhinav Parashar
  • 619
  • 4
  • 11
  • 27

8 Answers8

6

You could use a regular expression for it.

var str = "aabbrdfc0912",
    array = str.match(/..|./g);
console.log(array);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
2

One of the possible regex could be /[\w]{2}/g

var str = "aabbrdfc0912", splited_arr;

splitted_arr = str.match(/[\w]{2}/g);
console.log(splitted_arr);
Saba
  • 3,418
  • 2
  • 21
  • 34
1

You can use the match function and a small regex to do that:

var even_str = "aabbrdfc0912",
    odd_str = "aabbrdfc0912X";

console.log( splitInPairs(even_str) );
console.log( splitInPairs(odd_str) );

function splitInPairs(str) {
    return str.match(/..?/g);
}
blex
  • 24,941
  • 5
  • 39
  • 72
1

String.match(rg) would let you do this:

console.log("aabbrdfc0912".match(/\w\w/g))
Jai
  • 74,255
  • 12
  • 74
  • 103
1
var arr = str.match(/.{1,2}/g);

will give you result

["aa","bb","rd","fc","09","12"]; 
Jai
  • 74,255
  • 12
  • 74
  • 103
S M
  • 3,133
  • 5
  • 30
  • 59
0

For-loop with increment of 2 could be helpful.

var str = "aabbrdfc09123";;
var op = [];
for (var i = 0; i < str.length; i += 2) {
  op.push(str[i] + (str[i + 1] || ''));
}
console.log(op);
Rayon
  • 36,219
  • 4
  • 49
  • 76
0

Another solution using String.split, Array.slice and Array.forEach functions:

var str = "aabbrdfc0912", result = [];

str.split('').forEach(function(v, k, arr){
   if (k % 2 !== 0) this.push(arr.slice(k-1, k+1).join(''));
}, result);

console.log(result);  // ["aa", "bb", "rd", "fc", "09", "12"]

And one more approach with String.split and Array.filter methods:

result = str.split(/(\w{2})/).filter(Boolean);

console.log(result);  // ["aa", "bb", "rd", "fc", "09", "12"]
RomanPerekhrest
  • 88,541
  • 4
  • 65
  • 105
0

well, this can be done like this too instead of regex,

var str = "aabbrdfc0912";
var result = [];
var piece = 2;

while (str.length) {
  result.push(str.slice(0, piece));
  str = str.substr(piece);
}

console.log(result);
// result = ["aa","bb","rd","fc","09","12"];
azerafati
  • 18,215
  • 7
  • 67
  • 72