Start learning free

LESSON 68 OF 344 · STRINGS I

String Strip in JavaScript: trim, trimStart and trimEnd

Lesson Read the full explanation

In JavaScript, you can remove leading and trailing whitespace from a string using trim():

s.trim()        // removes leading and trailing whitespace
s.trimStart()   // removes only leading whitespace
s.trimEnd()     // removes only trailing whitespace

Here are some examples:

let s = "  hello  ";
console.log(s.trim());        // "hello"
console.log(s.trimStart());   // "hello  "
console.log(s.trimEnd());     // "  hello"

trim() returns a new string — the original is not modified.


Assignment
Follow the Coding Tutorial and trim whitespace from s!


Hint
Use s.trim() and assign the result to result.

STEP 1 OF 1
    Ctrl + Enter to check

    JAVASCRIPT · STRINGS I

    String Strip in JavaScript, explained

    What trimming does

    Text from the real world often has extra whitespace around it: a space left by a user typing into a form, a line break at the end of a line read from a file, a tab copied from a spreadsheet. Whitespace is invisible, but it makes strings different. "Alice " is not equal to "Alice".

    Other languages call this operation "strip". In JavaScript the method is trim(). It removes whitespace from the start and the end of a string, and leaves everything in the middle alone.

    s.trim()        // removes leading and trailing whitespace
    s.trimStart()   // removes only leading whitespace
    s.trimEnd()     // removes only trailing whitespace
    
    let s = "  hello  ";
    console.log(s.trim());        // "hello"
    console.log(s.trimStart());   // "hello  "
    console.log(s.trimEnd());     // "  hello"
    

    The quotes in the comments show where each result begins and ends, so you can see which spaces survive. Leading means at the front, trailing means at the back.

    Trim returns a new string

    Strings in JavaScript are immutable: no method can change a string that already exists. So trim() doesn't clean up s. It builds a new string and returns it. After the calls above, s still holds " hello ". To keep the cleaned text, store it:

    let name = "  Alice ";
    console.log(name.trim() === "Alice");   // true
    console.log(name === "Alice");          // false
    console.log(name.length);               // 8
    console.log(name.trim().length);        // 5
    

    If you write name.trim(); on a line by itself, the cleaned string is created and immediately discarded. Nothing changes, and no error is reported.

    What counts as whitespace

    Whitespace is more than the space bar. trim() also removes tabs, line breaks such as \n and \r, and other space characters, including the non-breaking space. A string like "\t\n hi \r\n" trims down to "hi".

    Only the ends are touched. Spaces between words stay: "a b".trim() is still "a b", with two spaces. A string made only of whitespace trims to the empty string "", and trimming an empty string is harmless.

    Removing inner spaces

    Because trim ignores the middle, you need another tool to deal with inner spaces. To delete all of them, use replaceAll. To squeeze runs of spaces into one, split on whitespace and join again:

    console.log(" a b ".replaceAll(" ", ""));                 // ab
    console.log("a  b   c".split(/\s+/).join(" "));          // a b c
    

    The exercise, step by step

    The starter code gives one variable with spaces on both sides:

    let s = "  hello  ";
    

    The task is to remove them.

    1. Choose the method. The spaces are on both sides, so trim() is the right one. trimStart() or trimEnd() would leave two spaces behind.
    2. Declare result below s, with let, and assign it s.trim().

    The solution in JavaScript

    let s = "  hello  ";
    
    let result = s.trim();
    

    Now result is "hello", with a length of 5, while s keeps its original two spaces on each side and a length of 9.

    Common mistakes

    The first mistake is expecting the original to change, as described above. The second is using the wrong side: if you only want to clean the front of a string, trimStart() is the precise choice, and trimEnd() for the back. A third mistake is hoping trim() will tidy the inside of a sentence. It won't, so use split and join or replaceAll for that.

    It also helps to trim before comparing. If a user types "yes " with a trailing space, a check such as answer === "yes" fails, while answer.trim() === "yes" succeeds. Combine it with toLowerCase() to ignore capital letters too.

    Trim and the other string tools

    Trimming usually comes first in a chain of string operations. Imagine reading a line of input such as " Alice, Bob ". If you split it on commas without cleaning it, the first name keeps its leading spaces and the last name keeps its trailing ones. Trimming the whole line first, and then each piece, gives names that you can compare, search for and count reliably.

    Because every string method returns a string, the calls chain naturally: input.trim().toLowerCase() removes the outer whitespace and then lowercases the result. Each step works on the output of the one before, and the original input is untouched throughout.

    Key takeaways

    • trim() removes whitespace from both ends, trimStart() from the front only, and trimEnd() from the back only.
    • Whitespace includes spaces, tabs and line breaks.
    • The result is a new string. The original is never modified, so store the result.
    • Spaces in the middle of the string are left alone.
    Keep going with JavaScriptAbout 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free