How to trim a string using JavaScript?

To remove spaces from a string using JavaScript, you can use the string.trim() method. The trim() method removes spaces from both ends of a given string without changing the original string. The characters to be removed include space, tab, page, and line terminators (' ', \t, \r, \n, etc). The method returns a new string without any leading or trailing whitespace. To remove spaces from a string, you can use the string.replace() method. Like the string.trim() method, the string.replace() method does not change the original string but returns a copy of the string with all occurrences of the searched value replaced with the new value (see example below). In this JavaScript Trim whitespace from the string example, we remove spaces using the string.trim() method. Click Execute to run the JavaScript Trim String online and see the result
How to trim a string using JavaScript? Execute
let str = "  JavaScript Trim Spaces Example    ";

console.log(str.trim());
Updated: Viewed: 762 times

How to trim strings on both sides in JavaScript?

To trim strings in JavaScript, you need to use the string.trim() method. The method removes all of the spaces and line separators both at the beginning and end of the string.

JavaScript trim() Syntax
string.trim()

Where:
  • string: the string from which spaces will be removed.

If you want to remove sequences of spaces and line separators only from the beginning of a string, you can use the string.trimStart() method:

JavaScript Trim String from the Beginning Example
let str = "     JavaScript Trim Spaces Example    ";

console.log(str.trimStart());

// output: JavaScript Trim Spaces Example    

If you want to remove sequences of spaces and line separators with line ends, you can use the string.trimEnd() method:

JavaScript Trim from Ending of String Example
let str = "     JavaScript Trim Spaces Example    ";

console.log(str.trimEnd());

// output:      JavaScript Trim Spaces Example

How to replace spaces in a JavaScript string?

The string.trim() method only removes whitespace from the string's beginning and end. If you want to remove occurrences in the middle of a string, use the method string.replace(). The replace() method returns a new string with the values replaced. The method does not change the original string. The RegExp modifier "/g" is used to find and replace all occurrences of a substring. If you don't pass "/g", only the first occurrence will be replaced.

JavaScript replace() Syntax
string.replace(regExp, newValue)

Where:
  • regExp: the substring or regular expression to search
  • newValue: the value to replace with
JavaScript Replace Spaces Example
let str = "  JavaScript Trim Spaces Example    ";

console.log(str.replace(/ /g, ""));

// output: JavaScriptTrimSpacesExample

See also