Last Updated : Jan 1, 2023
This function helps us to remove whitespace from the front and also from the end of the given string, in addition, we can also say that trim helps to remove additional whitespace from a string.
As of now, we understand what the basic use of trim is and for what purpose trim is used.
Is there one single method in trim to remove leading and trailing whitespace or two different functions which help us to remove whitespace from both sides differently?
var string = " Hello World! "; console.log(string.trim()); // prints "Hello World!"
As we see that this function removes extra whitespace from both sides that are left and right.
But what if we want to remove whitespace space from only one side then, what function will help us to remove extra whitespace? Let see:
// trim left function var string = " Hello world"; console.log(string.trimLeft(" ")); // prints "Hello world" // trim right function var string = "Hello world "; console.debug(string.trimRight(" ")); // prints "Hello world"
- One thing to note here is that the trim function is not only used to remove whitespace. This function also helps to remove a specific character from strings.
- In this tutorial, we only show you how to use the trim function to remove whitespace from a string, because this is the basic way to use the trim function.
- Now, in our above examples we see that we use the trim function on a required string to remove whitespace from that string.
- Whereas we use the trim left and trim right function on other required strings to remove whitespace from the left side and the right side respectively.