Languages
[Edit]
EN

JavaScript - String trim() method example

8 points
Created by:
Wiktor-Sribiew
830

In this short article, we are going to discuss how to trim strings in JavaScript.

There are 3 different ways to trim string:

  • both sides - most commonly used
  • left side
  • right side

Quick overlook:

Left and right side trimming with ECMAScript 2020:

 Note: trimStart, trimLefttrimEnd, trimRight are in draft of ECMAScript 2020, so it is better to use replace approach until the methods will be commonly supported.

More detailed and grouped substring methods description is placed below.

1. Documentation

Edit
Syntax
  • String.prototype.trim()
  • String.prototype.trimStart() or String.prototype.trimLeft()
  • String.prototype.trimEnd() or String.prototype.trimRight()
Parameters-
Result

The trim() method returns new string representing the string stripped of whitespace from both its beginning and end.

The trimStart() and trimEnd() methods return a new string with whitespace trimmed from just one side.

Description

The trim() method removes whitespace from both ends of a string and returns a new string, without modifying the original one. To trim just one side of the string use trimStart() or trimEnd().

2. Trim operation with built-in methods example

Edit

In this section, two ways how to trim strings in javascript are represented. One of them is based on String trim method. The second one replaces white characters with regular expressions.

3. Side trimming operation with built-in methods example

Edit

JavaScript API provides additionally left and right trimming.

3.1. Left side trimming

Edit

Note: trimStart and trimLeft are in draft of ECMAScript 2020, so it is better to use replace approach until the methods will be commonly supported.

3.2. Right side trimming

Edit

Note: trimEnd and trimRight are in draft of ECMAScript 2020, so it is better to use replace approach until the methods will be commonly supported.

Alternative titles

  1. JavaScript - String.prototype.trim() documentation with examples
  2. js - String trim() method documentation with examples
1
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.

JavaScript - String (documentation)

Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join