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.
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.
So here’s the example code that makes use of the trim() method:
var sentence = ' Coding Creativo '; sentence = sentence.trim(); console.log(sentence);