At times, we may get some string, with some spaces at the start, and the end, and we need to remove that. For example, there could be some name, and then there are a lot of spaces on both the ends of the string(as shown in the below example). So, in order to remove such spaces from the ends of the string, we can make use of the trim method.
Remember that this method is going to return a new string, removing the whitespaces from both ends. The original string is going to be as it was. Let’s try an example so that we can understand the trim method.
As you can see, the string here, has some whitespaces, on both the ends. In order to remove those, we have used the trim method. Remember that this method returns a new string with the removed whitespaces. The original string is as it was. Let’s have a look at the output –
As you can see, at first, the length of the string is 21, which includes the 10 whitespaces, and the 11 characters in ‘GyaniPandit’. But, we call the trim method on the string, and the whitespaces are removed from the string. You can try printing the string with and without the whitespaces, and observe the difference. The length of the string, after the whitespaces are removed, is going to be 11.