JavaScript - String trim() method example
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:
xxxxxxxxxx
var text = ' abc ';
// Both side trimming:
console.log( 'abc' === text.trim() ); // true
console.log( 'abc' === text.replace(/^\s*|\s*$/g, '') ); // true
// Left side trimming:
console.log( 'abc ' === text.replace(/^\s*/g, '') ); // true
// Right side trimming:
console.log( ' abc' === text.replace(/\s*$/g, '') ); // true
Left and right side trimming with ECMAScript 2020:
xxxxxxxxxx
var text = ' abc ';
// left side trimming:
console.log( 'abc ' === text.trimStart() ); // true
console.log( 'abc ' === text.trimLeft() ); // true
// right side trimming:
console.log( ' abc' === text.trimEnd() ); // true
console.log( ' abc' === text.trimRight() ); // true
Note:
trimStart
,trimLeft
,trimEnd
,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.
Syntax |
|
Parameters | - |
Result |
The The |
Description |
The |
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.
xxxxxxxxxx
var text = ' abc ';
console.log( 'abc' === text.trim() ); // true
console.log( 'abc' === text.replace(/^\s*|\s*$/g, '') ); // true
JavaScript API provides additionally left and right trimming.
xxxxxxxxxx
var text = ' abc ';
console.log( 'abc ' === text.replace(/^\s*/g, '') ); // true
console.log( 'abc ' === text.trimStart() ); // true
console.log( 'abc ' === text.trimLeft() ); // true
Note:
trimStart
andtrimLeft
are in draft of ECMAScript 2020, so it is better to use replace approach until the methods will be commonly supported.
xxxxxxxxxx
var text = ' abc ';
console.log( ' abc' === text.replace(/\s*$/g, '') ); // true
console.log( ' abc' === text.trimEnd() ); // true
console.log( ' abc' === text.trimRight() ); // true
Note:
trimEnd
andtrimRight
are in draft of ECMAScript 2020, so it is better to use replace approach until the methods will be commonly supported.