Remove Whitespace from Both Sides of a String with JavaScript | Plantpot

Remove Whitespace from Both Sides of a String with JavaScript

Web Dev
Sponsored links

In this article, I will introduce how to remove whitespace from both sides of a string with JavaScript.

The trim() method

To remove whitespace from both sides of a string in JavaScript, use the trim method.
The trim() method returns a string with both ends stripped.
The original string is unchanged.
Whitespace includes half-width spaces, tabs, line breaks, etc.

The syntax is below.

str.trim()

Below is sample code that removes whitespace from both sides of the string.

const str = '   Hello world!   ';

console.log(str);
// "   Hello world!   ";

console.log(str.trim());
// "Hello world!";