Trim a string in JavaScript

In this tutorial, I am going to discuss about three different string methods those are trim(), trimstart(), and trimend(). Those three methods are going to be used to remove the whitespace from both sides of a string or from the start or from the end.

By whitespace, I am talking about all the whitespace characters (no-break space, tab, space, etc..), and all the line terminator characters (CR, LF, etc..). These methods does not change or modify the original string, always returns a new string.

trim() method

This method removes whitespace from both sides of the string and returns a new string.

let string = '   Hey Codespeedy   ';
    console.log(string.trim());

As you can see in the above program, I have declared a variable named stringand assigned the string value ‘Hey Codespeedy’. Then I have called trim()method to remove the whitespace from both sides of the string.

Output

'Hey Codespeedy'

You can see, the trim()method removed the whitespace from both sides of the string and returned a new string string.

trimStart() method

This method removes the whitespace from starting or beginning of a string and returns a new string. This method can be used as the trimLeft() because this method removes whitespace from the left side also.

let string = '   Hey Codespeedy   '; 
    console.log(string.trimStart());

In the above program, I have called trimStart() method to remove the whitespace from the beginning or starting of the string.

Output: 

'Hey Codespeedy      '

As you can see, the trimStart() method removed the whitespace from the beginning or starting of the string and returned a new string.

trimEnd() method

This method removes the whitespace from the end of a string and returns a new string. This method can be used as the trimRight() because this method removes whitespace from the right side also.

let string = '    Hey Codespeedy   '; 
    console.log(string.trimEnd());

Now, this time I have called trimEnd() method to remove the whitespace from the end of the string.

Output

'      Hey Codespeedy'

The trimEnd() method removed the whitespace from the end of the string and returned a new string.

Notes

  • trim(), trimstart(), and trimend() methods do not remove the whitespace between the string.

Leave a Reply

Your email address will not be published. Required fields are marked *