Start learning free

LESSON 67 OF 344 · STRINGS I

String Split in JavaScript: Turning Text into an Array

Lesson Read the full explanation

In JavaScript, you can split a string into an array of substrings using split():

s.split(delim)     // splits on a delimiter string
s.split(regex)     // splits on a regular expression
s.split("")        // splits into individual characters

Here are some examples:

let sentence = "hello world foo";
let words = sentence.split(" ");
console.log(words);  // ["hello", "world", "foo"]

let csv = "a,b,c";
let parts = csv.split(",");
console.log(parts);  // ["a", "b", "c"]

You can loop through the resulting array:

words.forEach(w => console.log(w));

Assignment
Follow the Coding Tutorial and split sentence into an array of words!


Hint
Use sentence.split(" ") and assign the result to words.

STEP 1 OF 1
    Ctrl + Enter to check

    JAVASCRIPT · STRINGS I

    String Split in JavaScript, explained

    What split does

    The split() method cuts a string into pieces and returns them as an array. You tell it where to cut by passing a separator, called the delimiter. The delimiter itself is removed from the result.

    s.split(delim)     // split on a delimiter string
    s.split(regex)     // split on a regular expression
    s.split("")        // split into individual characters
    
    let sentence = "hello world foo";
    let words = sentence.split(" ");
    console.log(words);   // [ 'hello', 'world', 'foo' ]
    
    let csv = "a,b,c";
    let parts = csv.split(",");
    console.log(parts);   // [ 'a', 'b', 'c' ]
    

    The original string is not changed. Strings in JavaScript are immutable, and split builds a brand-new array.

    Working with the result

    Because you get an array, all the usual array tools apply. You can loop with forEach, count with length, or index into it:

    words.forEach(w => console.log(w));  // hello, world, foo, one per line
    console.log(words.length);            // 3
    console.log(words[0]);                // hello
    

    The opposite operation is join, which glues an array back into a string: "a,b,c".split(",").join("-") gives "a-b-c".

    Details that surprise people

    Empty pieces are kept

    Two delimiters in a row, or a delimiter at the very start or end, produce empty strings:

    console.log("a,,b".split(","));        // [ 'a', '', 'b' ]
    console.log("a b  c".split(" "));      // [ 'a', 'b', '', 'c' ]
    console.log(" a b ".split(" "));       // [ '', 'a', 'b', '' ]
    

    When words may be separated by several spaces, split on a regular expression instead. \s+ means "one or more whitespace characters":

    console.log("a b  c".split(/\s+/));    // [ 'a', 'b', 'c' ]
    

    Splitting an empty string

    "".split(",") returns [ '' ], an array with one empty string, not an empty array. But "".split("") returns [].

    Splitting into characters

    "abc".split("") gives [ 'a', 'b', 'c' ]. This works on UTF-16 code units, so an emoji, which takes two of them, is cut into two broken pieces. Spreading the string, [..."😀a"], splits by whole characters instead.

    Limiting the number of pieces

    An optional second argument caps the length of the array: "a,b,c".split(",", 2) gives [ 'a', 'b' ].

    No separator at all

    Calling split() with no argument does not split. It returns an array holding the whole string: "abc".split() is [ 'abc' ].

    The exercise, step by step

    The starter code gives one variable:

    let sentence = "hello world foo";
    

    The task is to break it into an array of words.

    1. Pick the delimiter. The words are separated by single spaces, so the delimiter is " ".
    2. Declare words below sentence, with let, and assign it sentence.split(" ").

    The solution in JavaScript

    let sentence = "hello world foo";
    
    let words = sentence.split(" ");
    

    Now words is ["hello", "world", "foo"] and words.length is 3. Notice that the delimiter needs quotes, since it is a string. Writing split(" ") with a space between the quotes matters: split("") with nothing between them would break the sentence into single letters.

    Common mistakes

    The first common mistake is expecting split to modify the string. It never does. The string stays whole, and the array is a separate value that you must store, which is why the lesson assigns it to words.

    The second is getting empty strings from messy input. Text typed by people often has double spaces or a trailing space, and a plain split(" ") turns each extra space into an empty element. If you then count words with length, the count is too high. Trim the string first with trim() and split on /\s+/ to get clean words.

    The third is choosing the wrong delimiter. A comma-separated line needs split(","), a line break needs split("\n"), and a sentence needs a space. The delimiter must match the text exactly. If it isn't found, you get an array with a single element holding the whole string, not an error:

    console.log("hello world".split(","));   // [ 'hello world' ]
    

    Where split fits

    Splitting is usually the first step in a short pipeline: split the text into pieces, work on each piece, then join them again. For example, capitalizing every word of a sentence means splitting on spaces, changing the first letter of each word with array methods, and joining with a space. Later lessons build on this idea, so it is worth being comfortable with what split returns before moving on.

    Key takeaways

    • split(delim) returns an array of the pieces between the delimiters, and the delimiters are left out.
    • The original string stays the same.
    • Repeated delimiters give empty strings. Use /\s+/ to split on runs of whitespace.
    • split("") separates characters, and join reverses a split.
    Keep going with JavaScriptAbout 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free