views:

40

answers:

2

I have random strings that are similar to this:

2d4hk8x37m

or whatever. I need to split it at every other character.

To split it at every character its simply:

'2d4hk8x37m'.split('');

But i need every other character so the array would be like this:

['2d', '4h', 'k8', 'x3', '7m']

Your help is appreciated. Thanks!

+1  A: 

There's no regex needed here. Just a simple for loop.

var hash = '2sfg43da'
var broken = [];
for(var index = 0; index < hash.length / 2; index++)
    broken.push(hash.substr(index*2, 2));
Alin Purcaru
This loops all chars and adds empty entries to the array after half are done. I'd imagine checking against a value before pushing will solve this.
Dale
bah! I forgot both `++` and `/2`. Thank you for noticing.
Alin Purcaru
The regex is much more expressive.
Vivin Paliath
@Vivin Yeah. I voted +1 on the regex ;). But I don't think you should use regexes for other than pattern matching.
Alin Purcaru
I would consider "every 2 characters" a pattern.
rchern
@rchern I would too, but this is not the case here because you don't match any 2 consecutive characters, but only about half of the possible matches.
Alin Purcaru
@Alin, no, the OP wants to match every 2 characters.
rchern
@rchern I was referring to your *"every 2 characters" a pattern*. I know what Dale wanted. And what he wanted does not qualify as pattern matching. What you did with your pattern is abuse the way the regex engine searches for matches. While I do consider that clever (and I probably would have used your regex approach), that does not make it pattern matching.
Alin Purcaru
@Alin, what I'm saying is that I do consider this to be pattern matching, thus using regex is valid.
rchern
+4  A: 
var string = "2d4hk8x37m";
var matches = string.match(/.{2}/g);
console.log(matches);
rchern
@Dale, the answer you accepted does not use .split() either. My answer gives you what you asked for, and in my opinion, is a better solution than the answer you accepted. *shrugs*
rchern
Awe, I hadn't tested your code since you fixed it. I will test performance then choose the correct answer.
Dale
@Dale, fixed it? What do you mean?
rchern
@rchern, the first time I checked your code it returned a number not the matches as an array, (silly me I didn't notice to remove .length). Vivin must have fixed it with the edit???
Dale
@Dale She was just outputting the number of matches found `matches.length` then. The matches were there.
Alin Purcaru
Yes, I was just using that to verify the correct length. Your code isn't going to have console.log there anyway...right? (;
rchern
@rchern right :) Thanks all for the help.
Dale