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:
// ONLINE-RUNNER:browser;
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:
// ONLINE-RUNNER:browser;
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.
1. Documentation
Syntax |
|
Parameters | - |
Result |
The The |
Description |
The |
2. Trim operation with built-in methods example
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.
// ONLINE-RUNNER:browser;
var text = ' abc ';
console.log( 'abc' === text.trim() ); // true
console.log( 'abc' === text.replace(/^\s*|\s*$/g, '') ); // true
3. Side trimming operation with built-in methods example
JavaScript API provides additionally left and right trimming.
3.1. Left side trimming
// ONLINE-RUNNER:browser;
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.
3.2. RightĀ side trimming
// ONLINE-RUNNER:browser;
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.