Js RegExp every other character

I have random lines like this:

2d4hk8x37m

or whatever. I need to break it into every other character.

To break it down into each character, simply:

'2d4hk8x37m'.split('');

But I need every other character, so the array will be like this:

['2d', '4h', 'k8', 'x3', '7m']
+3
source share
2 answers
var string = "2d4hk8x37m";
var matches = string.match(/.{2}/g);
console.log(matches);
+7
source

No regular expression is needed here. Just a simple loop.

var hash = '2sfg43da'
var broken = [];
for(var index = 0; index < hash.length / 2; index++)
    broken.push(hash.substr(index*2, 2));
+1
source

Source: https://habr.com/ru/post/1771533/


All Articles