JavaScript – Trim a String

To trim whitespaces from both the ends of a string in JavaScript, call trim() method on this string.

Syntax

The syntax to call trim() method on this string str is

str.trim()

trim() returns a new string with whitespaces trimmed from the original string.

ADVERTISEMENT

Examples

In the following example, we take a string str and trim the whitespaces at start and end of the string using trim().

index.html

Conclusion

In this JavaScript Tutorial, we learned how to trim whitespaces from the edges of a string in JavaScript, using trim() method, with examples.