totn JavaScript

JavaScript: String trim() method

This JavaScript tutorial explains how to use the string method called trim() with syntax and examples.

Description

In JavaScript, trim() is a string method that is used to remove whitespace characters from the start and end of a string. Whitespace characters include spaces, tabs, etc. Because the trim() method is a method of the String object, it must be invoked through a particular instance of the String class.

Syntax

In JavaScript, the syntax for the trim() method is:

string.trim();

Parameters or Arguments

There are no parameters or arguments for the trim() method.

Returns

The trim() method returns a string with whitespace characters removed from the start and end of the string.

Note

  • The trim() method does not change the value of the original string.

Example

Let's take a look at an example of how to use the trim() method in JavaScript.

For example:

var totn_string = '   TechOnTheNet   ';

console.log(totn_string.trim());

In this example, we have declared a variable called totn_string that is assigned the string value of 'TechOnTheNet'. We have then invoked the trim() method of the totn_string variable to remove the whitespace characters from the start and end of the string.

We have written the output of the trim() method to the web browser console log, for demonstration purposes, to show what the trim() method returns.

The following will be output to the web browser console log:

'TechOnTheNet'

In this example, the trim() method removed the whitespace characters from the start and end of the string '   TechOnTheNet   ' and returned a string value of 'TechOnTheNet'.