JavaScript String.prototype.trim() Method
The trim() method removes white space, including spaces, tabs and line breaks, from both ends of a string.
Description
The trim() method returns a new string with white space removed from both ends. White space includes spaces, tabs, non-breaking spaces and line terminators. It's commonly used to clean up form input before checking or saving it. Use trimStart() or trimEnd() to trim only one side.
It doesn't remove white space from the middle of a string; to collapse runs of spaces into one, use str.replace(/\s+/g, ' '). It also leaves zero-width characters alone, because they don't count as white space.
Trimming is worth doing before checking whether a required field is empty, since a value of only spaces would otherwise pass, and before comparing or storing values typed by users. Native form validation doesn't trim values for you.
Syntax
string.trim()Return Value
A new string with white space removed from both ends.
Example
Browser Support
The following information will show you the current browser support for the String.prototype.trim() method. Hover over a browser icon to see the version that first introduced support for this method.
Desktop





Tablets & Mobile





