JavaScript trim method

The trim method of JavaScript is used to remove the leading and trailing spaces in a given string.

This may be useful in scenarios where visitors are given options to enter text in textboxes or text area and they enter text with leading or trailing spaces or presenting database driven string and ensuring no white spaces are shown etc.

See a trim example
  • The trim JavaScript string method removes spaces from both sides, left and right of the string.
  • The trim method is compatible with almost all browsers except IE 8 and earlier versions.
  • The original string remains the same after using the JavaScript string trim method.

Syntax of trim method

Following is the syntax of using the trim method:

Str.trim();

Where Str is the string that you intend to remove whitespaces by using the trim method.

A trim method example

Following is a JavaScript trim example to remove whitespaces in a given string.

We have created a string Str with spaces at both sides of the string. After that, we will use the trim method to delete the spaces at both sides and will show the resultant string in an alert.

Experience this example online

Once you click the button “Show trim”, it will show you an alert after executing the trim function. You can see three spaces on both sides are removed and the string is shown without whitespaces.

JavaScript trim with the textarea example

In this example, a textarea is used where you can enter the text. After entering text with leading and/or trailing whitespaces, click the button “show trim” that will trigger JavaScript function.

It will execute the trim method and show an alert with the entered text after trim string function is executed. See example by clicking the link or image below:

Experience this example online

As you can see, two buttons are shown; one with trim and other without. For seeing the difference, enter text with the leading and/or trailing spaces and click both buttons to see how alert shows resultant string with and without trim method.