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

Viewed 104

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);

3 Answers

Try this:

const split = (str = "") => str.match(/.{1,2}/g) || [];
console.log( split("hello world") );

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

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

You can also increase number of spliting by editing {1,2} into number like 3, 4, 5 as in 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)); 

It is easier to use a match, but if you must use split you can use your solution with a capture group to keep the text where you split on, and remove the empty entries afterwards.

The pattern will be (..?) to match 2 times any char where the second char is optional using the queation mark.

console.log("hello world".split(/(..?)/).filter(Boolean));

Related