Why is this useful? Sometimes you wind up with a bunch of un-needed white space padding your strings – often from the end-user hammering the space key when a space isn’t required. Unnecessary white space can also occur after splitting strings or reading strings from a file.
Removing unneeded white space from strings before displaying them or storing them in a database keeps your data tidy and looking neat.
The syntax for using the trim() method on a string variable is as follows:
- string can be any string typed variable
- After the trim() method has been executed on the string, the trimmed string is returned.
- The original string variable is not modified!
Trim Method Example
Here’s some code that shows how the trim() method behaves. I’ll leave explanations in the comments:
# Define a string variable with a bunch of unnecessary white space at the beginning and end var myString = " spaces everywhere around me! "; # Assign the value returned from the trim() method to a new variable var myTrimmedString = myString.trim(); # When viewing the original string, you will notice that it has not been modified by trim() console.log(myString); # " spaces everywhere around me! " # The returned trimmed value was assigned to the new string variable console.log(myTrimmedString); # "spaces everywhere around me!"
… and that’s pretty much all there is to it. Simple but very useful!