What are elegant ways to pair characters in a string?
algorithm, javascript, string
Solution
How about:
var array = ("0123456789").match(/\w{1,2}/g);
Here we use `.match()` on your string to match any two or single (`{1,2}`) word characters (`\w`) and return an array of the results.
Regarding your edit for a non-regex solution; you could do a far less elegant function like this:
String.prototype.getPairs = function()
{
var pairs = [];
for(var i = 0; i < this.length; i += 2)
{
pairs[pairs.length] = this.substr(i, 2);
}
return pairs;
}
var array = ("01234567890").getPairs();
Problem
For example, if the initial string `s` is `"0123456789"`, desired output would be an array `["01", "23", "45", "67", "89"]`. Looking for elegant solutions in JavaScript. What I was thinking (very non-elegantly) is to iterate through the string by splitting on the empty string and using the Array.forEach method, and insert a delimeter after every two characters, then split by that delimeter. This is not a good solution, but it's my starting point. Edit: A RegExp solution has been posted. I'd love to see if there are any other approaches.