Ship internal tools in hours, not weeks. Real auth, users, jobs, audit logs, and cohesive UI included. Early access $249 $499 → [Get it now]

How to split a string by spaces in JavaScript

Splitting strings by spaces is fundamental for word processing, search functionality, text analysis, and implementing features like word count or keyword extraction in JavaScript applications. With over 25 years of experience in software development and as the creator of CoreUI, I’ve implemented space-based string splitting in components like search bars, tag inputs, and text analyzers where breaking sentences into individual words enables powerful text processing capabilities. From my extensive expertise, the most straightforward and reliable solution is using the split() method with a space character as the separator. This approach is simple, efficient, and handles the common use case of converting sentences into word arrays.

Use the split() method with a space separator to break a string into an array of words.

const sentence = 'hello world javascript'
const words = sentence.split(' ')
// Result: ['hello', 'world', 'javascript']

The split(' ') method divides the string at each space character, creating an array where each word becomes a separate element. In this example, 'hello world javascript'.split(' ') produces ['hello', 'world', 'javascript']. This method preserves the original words exactly as they appear, including any punctuation attached to them. If there are multiple consecutive spaces, empty strings will appear in the resulting array for each extra space.

Best Practice Note:

This is the same approach we use in CoreUI React components for processing search queries, creating tag systems, and implementing text-based filtering across our component library. For handling multiple spaces or other whitespace, use regex: sentence.split(/\s+/) which splits on any whitespace and ignores multiple consecutive spaces. When dealing with user input, use .trim() before splitting to avoid unexpected empty strings from leading or trailing spaces: sentence.trim().split(/\s+/). For more general string-to-array techniques, see how to convert a string to an array in JavaScript.


Speed up your responsive apps and websites with fully-featured, ready-to-use open-source admin panel templates—free to use and built for efficiency.


About the Author