- Instant help with your JavaScript coding problems

Remove spaces from string at the beginning, end, or both in JavaScript

Question:
How to remove spaces from string at the beginning, end, or both in JavaScript?
Answer:
const str = '  This is a text with extra whitespeces   ';
const cleanStr = str.trim();
console.log(cleanStr); // This is a text with extra whitespeces
Description:

To remove unwanted spaces from a string from both its beginning and end use the trim method. 

The trim() method removes whitespace from both ends of a string and returns a new string, without modifying the original string. Whitespace in this context is all the whitespace characters (space, tab, no-break space, etc.) and all the line terminator characters (LF, CR, etc.).

The trim method also has two subvariants when you want to remove unnecessary space characters only from the beginning trimStart or end trimEnd of the text.

Reference:
The trim reference
Share "How to remove spaces from string at the beginning, end, or both in JavaScript?"
Related snippets:
Tags:
remove, delete, space, whitespace, string, beginning, end, javascript, trailing
Technical term:
Remove spaces from string at the beginning, end, or both in JavaScript