Start learning free

LESSON 69 OF 348 · STRINGS I

String Split in TypeScript: split() into Arrays

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

    TYPESCRIPT · STRINGS I

    String Split in TypeScript, explained

    Breaking a string into pieces

    The split method cuts a string at every place a separator appears and returns the pieces as an array of strings. In TypeScript the result has the type string[].

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

    The separator itself is not part of any piece:

    let sentence: string = "hello world foo";
    let words: string[] = sentence.split(" ");
    console.log(words); // [ 'hello', 'world', 'foo' ]
    
    let csv: string = "a,b,c";
    let parts: string[] = csv.split(",");
    console.log(parts); // [ 'a', 'b', 'c' ]
    

    Once you have an array, you can read pieces by index, check words.length and loop over the items:

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

    This prints hello, world and foo, each on its own line.

    The exercise

    The starting code defines the sentence:

    const sentence: string = "hello world foo";
    

    The task is to break it into words and keep them in a variable named words, typed string[].

    1. Declare words below sentence with the type string[], an array of strings.
    2. Call split(" ") on sentence, using a single space as the separator.
    3. Assign the result to words.

    The finished code:

    const sentence: string = "hello world foo";
    
    const words: string[] = sentence.split(" ");
    

    Now words holds three strings, "hello", "world" and "foo", and words.length is 3. The original string is untouched.

    Behaviours to know

    • Splitting on "" gives characters. "abc".split("") returns ['a', 'b', 'c']. This splits by UTF-16 code unit, so an emoji, which takes two units, is cut into two broken halves. The spread form [..."abc"] goes by whole characters instead.
    • Repeated separators produce empty strings. A single space is the delimiter, not "any whitespace", so two spaces in a row leave an empty piece between them:
    console.log("a  b".split(" "));    // [ 'a', '', 'b' ]
    console.log("a  b".split(/\s+/));  // [ 'a', 'b' ]
    

    The regular expression /\s+/ means "one or more whitespace characters", and it also covers tabs and line breaks. A space at the start or end of a string also produces an empty first or last piece: " a ".split(" ") returns ['', 'a', ''].

    • An empty string. "".split(",") returns [''], an array with one empty string, not an empty array. "".split("") does return [].
    • A limit. A second argument caps the number of pieces: "a,b,c,d".split(",", 2) returns ['a', 'b']. The rest of the string is dropped, not kept in the last piece.
    • The separator is required in practice. Calling split() with no argument compiles only with a type error, and the result is a one-item array holding the whole string. Always pass a separator.
    • The pieces are strings. "1,2,3".split(",") gives ['1', '2', '3'], not numbers. Convert them with Number or map(Number) if you need to add them.

    Splitting and then using the pieces

    A typical use of split is reading a line of data. Array destructuring gives each piece a name:

    const line: string = "ana,25,paris";
    const [person, age, city] = line.split(",");
    
    console.log(person, city);   // ana paris
    console.log(Number(age) + 1); // 26
    console.log(age + 1);         // 251
    

    The last two lines show why converting matters: age is the string "25", so adding 1 to it joins text and gives "251".

    Splitting pairs naturally with join, which does the opposite and glues an array back into one string with a separator between the items. Together they reverse the words of a sentence:

    const sentence: string = "the quick brown fox";
    console.log(sentence.split(" ").reverse().join(" ")); // fox brown quick the
    

    Reading beyond the end of the array behaves like any array: sentence.split(" ")[10] is undefined, and length tells you how many words there really are.

    Choosing a separator

    Decide what separates the pieces before you write the call. A fixed character such as a comma, a dash or a newline ("\n") works with a plain string. Irregular spacing, or several kinds of whitespace, is better handled with /\s+/. If the string might start or end with spaces, call trim() first so you don't get empty pieces at the edges. Whatever you choose, test it on an input with a missing value, such as "a,,c", which gives ['a', '', 'c'].

    Key takeaways

    • split(delim) returns a string[] of the pieces between the delimiters.
    • split("") gives individual characters, and a regular expression such as /\s+/ handles runs of whitespace.
    • Adjacent delimiters create empty strings in the result.
    • The original string doesn't change, and the pieces stay strings.
    Keep going with TypeScriptAbout 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free