How to use the JavaScript trim Method, with Examples

JavaScript trim

This easy tutorial will show you how to use the JavaScript string trim() method and give some example usage.

The trim()* method is available to any string type variable in JavaScript. It removes any white space (spaces, tabs, newlines) found at the beginning and the end of the string.

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.

JavaScript Trim Method Syntax

The syntax for using the trim() method on a string variable is as follows:

string.trim()

Note that:

  • 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!

You can view more information on the trim() method in the Mozilla developer documentation.

SHARE:
nv-author-image

Brad Morton

I'm Brad, and I'm nearing 20 years of experience with Linux. I've worked in just about every IT role there is before taking the leap into software development. Currently, I'm building desktop and web-based solutions with NodeJS and PHP hosted on Linux infrastructure. Visit my blog or find me on Twitter to see what I'm up to.

Leave a Reply

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