Learn JavaScript trim method to remove spaces with 2 examples

Purpose of trim in JavaScript

The JavaScript trim method is used to remove the leading and trailing spaces in strings of JavaScript. For example, consider the following sentence:

 

The spaces before “This” and after the word “tutorial” will be removed after using the trim method:

 

The returned string will be:

“ This is trim method tutorial”

Note: the original string remains the same after using the trim method.

Syntax of trim JavaScript method

This is how you can use the trim method:

 

e.g.

 

So the trimmed_string will hold the string without spaces at both sides while String_to_remove_spaces remains the same.

To understand it better, see the following example to use the trim method.

An example to use trim method

In this example, I have created a string with leading and trailing spaces. After that, JS trim method is used to remove the spaces.

The string is displayed in a div element so you can see the difference before and after using the trim method. See the example and code online:

JavaScript trim

See online demo and code

At the click event of the button, a JS function is called where the trim function is used to delete the spaces before and after the string. To see the difference, the source string is displayed as web page loads. As you click the button, the trimmed string is shown by using the document.getElementById(“strtrimmed”).innerHTML statement.

Following JS code is used in <script> section:

 

You can see the complete code with markup in the demo page.

An example of using trim JavaScript function with user entered text

Generally, you may require using the trim method in scenarios where you have to make sure that no spaces are included in the text before the first word or after the last word. For example, in a feedback form’s textarea, where a user may accidently enter some spaces.

So before sending an email or saving data in the database, you can use the trim method to ensure that no leading or trailing spaces are sent or saved.

In the following example, a text area is used where you may enter some text. A line of string with spaces before and after the text is also used. As you click the button, “Execute trim method”, the alert will show the original text and the text after executing the trim method. See the difference in online example:

JavaScript trim textarea

See online demo and code

You can see, three alerts are shown as you click the button. The first alert shows the string before using the trim method. The second alert shows the string after using the trim method. While the third is to show you the original string remains the same after using the trim method on a string.

The following JS code is used in a function:

 

Similarly, you can use the textbox to get text and trim by using the JavaScript trim method.