How do you trim text in javascript?

Example 1

Remove spaces with trim():

let text = "       Hello World!        ";
let result = text.trim();

Try it Yourself »

Remove spaces with replace() using a regular expression:

let text = "       Hello World!        ";
let result = text.replace(/^\s+|\s+$/gm,'');

Try it Yourself »


Definition and Usage

The trim() method removes whitespace from both sides of a string.

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


Syntax

Parameters

Return Value

Type Description
A string A string with removed whitespace from both ends.



Browser Support

trim() is an ECMAScript5 (ES5) feature.

ES5 (JavaScript 2009) fully supported in all browsers:

Chrome IE Edge Firefox Safari Opera
Yes 9-11 Yes Yes Yes Yes


How do you trim text in javascript?


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'.

The trim() is a built-in string function in JavaScript, which is used to trim a string. This function removes the whitespace from both the ends, i.e., start and end of the string. As the trim() is a string method, so it is invoked by an instance of the String class. We have to create an instance of String class with which the trim() method will be used.

Note - The trim() method does not change the original string; it just removes the leading and trailing whitespace character.

Syntax

The syntax of trim() method is as follows:

Here, str is a String class of object that will contain the string to be trimmed.

Parameters

The trim() method does not have any arguments or parameters inside it.

Return Value

The string.trim() function returns the string after removing whitespace character from that string from the beginning and end of the string.

Examples

Below are some examples, which are using trim() function to remove the elements from it. In these examples, you will see how to use this JavaScript function. So, here are a few examples -

Example 1

In this example, we will pass a string containing whitespace at both ends.

A good practice when using string values from form fields is to remove the whitespaces from the start and end of the strings — i.e. trim the string.

In this post, I'm going to describe what is a whitespace and a line terminator character in JavaScript.

Plus, you'll read how to trim strings, aka remove whitespaces and line terminator characters from the start and/or end of the string.

1. The whitespaces and line terminators

Before diving into the actual trim functions, let's first agree what special characters the trim functions are removing from strings.

First, the whitespace is any character from the following list:

  • SPACE (U+0020 code point)
  • CHARACTER TABULATION (U+0009 code point)
  • LINE TABULATION (U+000BU code point)
  • FORM FEED (FF) (U+000C code point)
  • NO-BREAK SPACE (U+00A0 code point)
  • ZERO WIDTH NO-BREAK SPACE (U+FEFFU code point)
  • Any other character from Space Separator category

In simple words, the whitespaces are characters that rendered on the screen create an empty white space.

Common whitespace characters are space ' ' and tab '\t'.

Secondly, the line terminator is also a special set of characters consisting of:

  • LINE FEED (U+000A code point)
  • CARRIAGE RETURN (U+000D code point)
  • LINE SEPARATOR (U+2028 code point)
  • PARAGRAPH SEPARATOR (U+2029 code point)

The line terminator represents a character that exists at the end of a text line and has some special purpose.

A common line terminator character is the line feed '\n', which means moving one line forward.

2. Trim strings in JavaScript

There are situations when you want to clean strings entering from the application input. For example, you'd definitely want to trim strings from the form fields representing a username, first name, last name, phone number, etc.

JavaScript provides 3 simple functions on how to trim strings.

2.1 string.trim()

string.trim() removes sequences of whitespaces and line terminators from both the start and the end of the string.

Let's see a few examples:

javascript

const name = ' Kate ';

name.trim(); // => 'Kate'

const phoneNumber = '\t 555-123\n ';

phoneNumber.trim(); // => '555-123'

Try the demo.

name.trim() removes the spaces from the start and end of the string. ' Kate ' becomes 'Kate'.

phoneNumber.trim() also cleans boths ends: '\t 555-123\n ' becomes '555-123'.

The trim function removes from both ends of the string sequences of consecutive white spaces and line terminals. But if a whitespace is found in between two letters, then, of course, this whitespace is preserved:

javascript

const fullName = ' Kate Smith ';

fullName.trim(); // => 'Kate Smith'

Try the demo.

fullName.trim() removes the spaces from both the start and end of the string, however keeps the space between Kate and Smith words.

2.2 string.trimStart()

string.trimStart() removes sequences of whitespaces and line terminators only from the start of the string.

javascript

const name = ' Jane ';

name.trimStart(); // => 'Jane '

const phoneNumber = '\t 555-123 \n';

phoneNumber.trimStart(); // => '555-123 \n'

Try the demo.

name.trimStart() removes the spaces only from the start of the string, and doesn't touch the space at the end. ' Jane ' becomes 'Jane '.

phoneNumber.trimStart() removes the sequence of whitespaces and line terminals from the start only. '\t 555-123 \n' becomes '555-123 \n'.

2.3 string.trimEnd()

string.trimEnd() removes sequences of whitespaces and line terminators only from the end of the string.

javascript

const name = ' Jim ';

name.trimEnd(); // => ' Jim'

const phoneNumber = '\t 555-123 \n';

phoneNumber.trimEnd(); // => '\t 555-123'

Try the demo.

name.trimEnd() removes the one space from the end, and doesn't touch the leading part. ' Jim ' becomes ' Jim'.

phoneNumber.trimEnd() trims the end of the string too. '\t 555-123\n ' becomes '\t 555-123'.

3. Conclusion

The whitespaces, like a space or tab, are special characters that create empty space when rendered.

Also the line terminals, like the line feed, you may find at the end of lines in a multiline string.

Often you may find it useful to remove these special characters from a string. The JavaScript trim functions can help you.

string.trim() removes sequences of white spaces and line terminators from both the start and end of the string, string.trimStart() removes them from start, and finally string.trimEnd() removes them from the end.

Does JavaScript have a trim function?

The trim() is a built-in string function in JavaScript, which is used to trim a string. This function removes the whitespace from both the ends, i.e., start and end of the string. As the trim() is a string method, so it is invoked by an instance of the String class.

How do you trim space between words in JavaScript?

JavaScript String trim() The trim() method removes whitespace from both sides of a string.

How do you trim the value of a string?

The trim() method in Java String is a built-in function that eliminates leading and trailing spaces. The Unicode value of space character is '\u0020'. The trim() method in java checks this Unicode value before and after the string, if it exists then removes the spaces and returns the omitted string.

What trim () in string does?

The Trim method removes from the current string all leading and trailing white-space characters. Each leading and trailing trim operation stops when a non-white-space character is encountered. For example, if the current string is " abc xyz ", the Trim method returns "abc xyz".