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.
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.
You could use a regular expression for it.
var str = "aabbrdfc0912",
array = str.match(/..|./g);
console.log(array);
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);
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);
}
String.match(rg)
would let you do this:
console.log("aabbrdfc0912".match(/\w\w/g))
For-loop
with increment of2
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);
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"]
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"];