JavaScript trim method is used to remove whitespace from the beginning and end of a string. Then the trim() method cleans the string of any blanks entered incorrectly.

These characters may also have been entered for example through a prompt or an input box. Therefore it may be necessary to eliminate them.

The syntax of this method is quite simple, in fact you simply call the method on the string you want to clean up: string.trim().

Where string therefore represents the string to be manipulated.

As you can see from its syntax, the method takes no parameters.

But be careful, the trim method is not supported on some browsers and in this case it is necessary to use a function created ad hoc to be able to remove the excess spaces.

Banner Pubblicitario

JavaScript Trim – example

So let’s take a simple example of using this method.

We take as input an example string ‘Creative Coding’ with blank spaces inserted at the beginning and end and for convenience we display it in the browser console.



var sentence = '   Coding Creativo  ';
console.log(sentence);

We will notice that the example string is displayed with all its spaces.

Therefore, if we apply the JavaScript trim method to the string, we realize that both the leading and trailing spaces have been eliminated.

So here’s the example code that makes use of the trim() method:



var sentence = '   Coding Creativo  ';
sentence = sentence.trim();
console.log(sentence);

Conclusion

In this lesson we have simply seen what the JavaScript trim method, used on text strings, is useful for. In the next lessons we will see other ways to remove empty spaces from the beginning and end of a string.

Some useful links

JavaScript tutorial

Banner pubblicitario

JavaScript Calculator

Object in JavaScript

For in loop

Caesar cipher decoder

Slot Machine in JavaScript

Introduction to JavaScript language

Learn JavaScript – basic concepts

JavaScript variables and costants