The string is a simple text or characters which can include the alphabets, numbers, or symbols.
Javascript’s trim() method trims the extra white space from both sides of the strings. Extra white space can be space or tab, etc.
Syntax
Syntax for the trim() method is as follows:
In javascript’s trim string method, we simply call the function over a string, and it trims the string into a clean, space free string. This function doesn’t take any arguments.
Let’s try some examples and understand it.
Examples
First, we suppose a string and add some extra white space around the string.
Now, to get rid of the extra white spaces from both sides, we try to apply the trim() method over that string and see how it works.
We can see in the output that the string is trimmed and there is no extra whitespace left around the string as we desired it to happen.
Now, a question arises: what if we want to trim the string from only the left side or the start of the string and vice versa. There is a built-in function for that as well. There are two different trimStart() and trimLeft() functions, but these both do the same task. So, if we want to trim the string from the left side only and want to keep the whitespaces on the right side. We can use the trimStart() or trimtrimLeft() function.
As you can see that both functions do the same task and trim the strings from the left side only.
Similarly, if we want to trim the string from the last or the right side only. We can use any of the trimEnd() or trimRight() functions.
It is observed that the string is trimmed only from the right side, as we expected.
So, this is how the javascript’s built-in functions trim(), trimStart(), trimLeft(), trimEnd() and trimRight() works and helps us in getting rid of the extra whitespace around the string.
Conclusion
In this article, we have learned about javascript’s built-in string trim() function and see it’s various implementations. We have also learned about the trimStart() and trimEnd() functions. This article includes profound and explained in-depth knowledge, the need, and the usage of the javascript’s string trim function. So, keep on learning javascript with linuxhint.com.
from Linux Hint https://ift.tt/3msYHIF
0 Comments