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
1
2
3
console.log("Saint Louis ".trim());
console.log(" Saint Louis".trim());
console.log(" Saint Louis ".trim());

Console 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.

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

Console Output