Search code examples
javascriptsplit

How can I split a string into an array of 2 character blocks in JS?


For example, when given "hello world", I want [ "he", "ll", "o ", "wo", "rl", "d" ] returned.

I've tried "hello world".split(/../g), but it didn't work, I just get empty strings:

console.log("hello world".split(/../g));

I've also tried using a capture group which makes me closer to the goal:

console.log("hello world".split(/(..)/g));

The only real solution I can think of here is to prune out the empty values with something like this:

let arr = "hello world".split(/(..)/g);

for (let i = 0; i < arr.length; i++) {
    if (arr[i] === "") arr.splice(i, 1);
}

console.log(arr);

Even though this works, it's a lot to read. Is there a possible way to do this in the split function?

Other attempted solutions

let str = "hello world";
let arr = [];
for (let i = 0; i < str.length; i++) {
    arr.push(str[i++] + (str[i] || ''));
}
console.log(arr);


Solution

  • You can use .match() to split a string into two characters:

    var str = 'hello world';
    console.log(str.match(/.{1,2}/g));

    You can also increase the number of splitting by editing {1,2} into numbers like 3, 4, and 5 as in the example:

    3 characters split:

    var str = 'hello world';
    console.log(str.match(/.{1,3}/g));

    4 characters split:

    var str = 'hello world';
    console.log(str.match(/.{1,4}/g));