Split JavaScript String Into Array

- 1 minute read

This is a tiny snippet demonstrating how you can split a JavaScript string into an array:

const toArray = (string) => {
    return string.split(/[^a-zA-Z-]+/).filter(Boolean);
};

You can use it like this:

const sentence = `The ball is red.`;

const words = toArray(sentence);

In the above example, toArray(sentence) will output ["The", "ball", "is", "red"] to the words variable.

This snippet splits the string by spaces, but you can specify another RegEx parameter to the split() method in the toArray() function that will split the string by another delimiter.

Link to this section A one-line string splitter

You can also do the exact same thing with just one line of code:

const toArray = (string) => string.split(/[^a-zA-Z-]+/).filter(Boolean);

Link to this section Conclusion

That’s all!

I hope you enjoyed this quick little snippet. I’ve found it pretty handy to collect these snippets and have them on standby for when they need to be pasted into your codebase.