How to use javascript trim string method to remove spaces

The 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 text 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 javascript string trim method.

Syntax of trim in javascript

Following is the syntax to use 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 resultant string in an alert. See example by clicking the link below:

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 at both sides are removed and string is shown without whitespaces.

Javascript trim with 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 JS trim method and show an alert with the entered text after trim string function is executed. See example by clicking the link 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 leading and/or trailing spaces and click both buttons to see how alert shows resultant string with and without Javascript trim method.

Also see Javascript String | Javascript substring | Javascript replace

Was this article helpful?

Related Articles

Leave A Comment?