2

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

0

3 Answers 3

2

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

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you so much! This works as expected so I will accept this answer.
@LoganDevine Glad to help. :)
2

Try this:

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

Comments

1

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

2 Comments

What does .filter(Boolean) do? Finds truthy values?
@LoganDevine Yes, that is correct. You could also do console.log("hello world".split(/(..?)/).filter(s => s));

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.