Trimming Strings in Javascript

Trimming functions are natively available in Javascript. You don't need libraries to trim strings.

Trimming from Both Ends with trim

The trim method removes whitespace characters from both ends of a string. Whitespace characters are characters that are not seen in the screen :

  • space " "
  • tab "\t"
  • line feed "\n"
  • carriage return "\r"
var str = "  Hello World  ";

// outputs "Hello World"
console.log(str.trim());
// multi-line string using ES6 template literals 
var str = `
	Hello World  
`;

console.log(str.trim());

// outputs
"Hello World"

Trimming from the Beginning with trimStart

The trimStart methods removes whitespace characaters only from the beginning (left side) of a string. Whitespace characters are the same as trim method.

var str = "  Hello World  ";

// outputs "Hello World  "
console.log(str.trimStart());
// multi-line string with template literals
var str = `
	Hello World  

`;

console.log(str.trimStart());

// outputs 
"Hello World  

"

Trimming from the End with trimEnd

The trimEnd methods removes whitespace characters only from the end (right side) of a string. Whitespace characters are the same as trim method.

var str = "  Hello World  ";

// outputs "  Hello World"
console.log(str.trimEnd());
// multi-line string with template literals
var str = `
	Hello World  

`;

console.log(str.trimEnd());

// outputs 
"
	Hello World"
Loading Comments