trim ExamplesΒΆ

The general syntax for this method is:

stringName.trim();

This method returns a copy of the string with any leading or trailing whitespace removed. Whitespace characters are those that do not display anything on the screen, such as spaces and tabs.

Example

1console.log("Saint Louis ".trim());
2console.log(" Saint Louis".trim());
3console.log(" Saint Louis ".trim());

Output

Saint Louis
Saint Louis
Saint Louis

Example

When typing an email address into a web site, a user may inadvertently type a space before and/or after the email address. We can clean up such input using the trim method.

This example cleans up user input with trim.

let input = " [email protected] ";
let email = input.trim();
console.log(email);

Output