Remove Whitespace from Both Sides of a String with JavaScript

02/16/2022
Contents
In this article, you will learn 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!";