Skip to content

Trim String in JavaScript

Today we are going to see how to smash the whitespaces from the String in JavaScript. First let’s see how the whitespaces are created,

  • Space
  • Tab
  • Line terminator character (used to improve the readability of the source text)

So, the trim() method removes whitespaces from both the sides of the String. It doesn’t changes the original String.

Syntax

string.trim();

Trim Spaces:

' Hi Poopcoder!'.trim();   //'Hi Poopcoder!'
'Welcome '.trim();         //'Welcome'
' to learning '.trim();    //'to learning'

Trim Multi-line String:

In JavaScript, Template Literals helps us to create multi-line string. It’s not big surprise that trim method is works with this.

let multiLine = `
	Hai
	
	`;
	
multiline.trim(); // "Hai"
let multiLine = `
Let

trim multiline

	
`;
multiline.trim(); 
/*
Let

trim multiline*/

Trim Line Terminator Characters

Below are some examples for Line Terminator Characters, to know more details about Line Terminator click on

'Hi \n'.trim();         // "hi"

'JavaScript \t'.trim(); // "JavaScript"
	
'Lovers! \r'.trim();    // "Lovers!"

Trim Aliases

trimStart() removes the leading white space. So all the whitespace from the beginning of a string to the first non-whitespace character will be trimmed. trimLeft() is an alias of this method

let string = "   hi   ";
	
string.trimStart(); // "hi   "
string.trimLeft();  // "hi   "

trimEnd() removes the trailing whitespace. So all the whitespace from the end of a string will be trimmed. The alias of this method is trimRight().

let string = "   hi   ";
	
string.trimEnd();   // "   hi"
string.trimRight(); // "   hi"

trimStart() and trimEnd() are preferred and recommended to use with new ECMAScript code, trimLeft() and trimRight() are compatibility with old code.

You can also use it to remove odd whitespaces in a sentence and format it properly. It makes you sentence much prettier

let sentence = "He  threw    three free  throws ";

const prettySentence = sentence
    .split(' ') // ["He", "", "threw", "", "", "three", "free", "", "throws", ""]
    .filter(word => word) // ["He", "threw", "three", "free", "throws"]
    .join(' '); // "He threw three free throws"

console.log(prettySentence); // "He threw three free throws"

If your browser doesn’t supports the trim() method, you can use the below Regular Expression to remove whitespace in your string.

replace(/^\s+|\s+$/gm,'')

Browser Support:

  • trim() – Chrome, Firefox, Safari, Edge, Internet Explorer
  • trimStart() and trimEnd() –  Chrome, Firefox, Safari, Edge

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.