String trim() method in JavaScript

trim method in javascript

You can use the JavaScript trim method for removing whitespaces from both sides of a string. Whitespace in this context is all the whitespace characters (space, tab, no-break space, etc.) and all the line terminator characters (LF, CR, etc.). The trim() method does not affect the value of the string itself.
The trim method is used most commonly. Often users unknowingly add whitespaces into inputs. So in such cases, we can use the trim method to remove whitespaces.

Syntax:

string.trim();

Example:

var str = ” Hello World! “;
console.log(“‘” + str.trim() + “‘”);

Output:

‘Hello World!’

**Note: In above and below examples observe the whitespaces are getting trimmed from either both, left or right sides.

trimStart():

The trimStart() method removes whitespace from the beginning of a string. trimLeft() is an alias of this method.

Example:

var str = ” Hello World! “;
console.log(“‘” + str.trimStart() + “‘”);

Output:

‘Hello World! ‘

trimLeft():

The trimLeft() method removes whitespace from the beginning of a string. trimStart() is an alias of this method.

Example:

var str = ” Hello World! “;
console.log(“‘” + str.trimLeft() + “‘”);

Output:

‘Hello World! ‘

trimEnd():

The trimEnd() method removes whitespace from the end of a string. trimRight() is an alias of this method.

Example:

var str = ” Hello World! “;
console.log(“‘” + str.trimEnd() + “‘”);

Output:

‘ Hello World!’

trimRight():

The trimRight() method removes whitespace from the end of a string. trimEnd() is an alias of this method.

Example:

var str = ” Hello World! “;
console.log(“‘” + str.trimRight() + “‘”);

Output:

‘ Hello World!’

Conclusion:

You can use the JavaScript trim method for removing whitespaces from both sides of a string.
The trimStart() & trimLeft() method removes whitespace from the beginning of a string. trimLeft() is an alias of this method.
The trimEnd() & trimRight method removes whitespace from the end of a string. trimRight() is an alias of this method.

Leave a Reply