How to Remove Spaces from a String Using the trim() Function

Removing whitespace from the beginning or end of a string in JavaScript is simple and fast. To trim spaces from the start of a string, use the trimStart() function; to trim from the end, use trimEnd(). To remove spaces from both sides at once, use trim().

const string = " hi "; string.trimStart(); // Result: "hi "
string.trimEnd(); // Result: " hi"
string.trim(); // Result: "hi"

Return Value

Methods such as trim(), trimStart(), and trimEnd() in JavaScript return a new string without modifying the original one. For example:

const string = " hi ";
string.trimStart(); // "hi "
string.trimEnd(); // " hi"
string.trim(); // "hi"
console.log(string); // " hi "

Whitespace Characters

These methods remove various types of whitespace characters, including:

  • Space

  • Tab

  • Non-breaking space

  • Line break characters

Line break characters

Examples of trim() handling line breaks:

'hi \n'.trim(); // "hi"
'hi \t'.trim(); // "hi"
'hi \r'.trim(); // "hi"

Multiline Strings

In multiline template literals, trim() also effectively removes unnecessary whitespace:

const multiLine = `
hi

`;

multiLine.trim(); // "hi"

Words and Internal Spaces

The trim() method does not affect spaces between words:

const multiLine = `
hi

there

`;

multiLine.trim();
/*
вернет:
"hi

there"
*/

Aliases

trimStart() and trimEnd() are also known as trimLeft() and trimRight(), respectively. However, using trimStart() and trimEnd() is recommended in modern code for better readability and consistency with current JavaScript standards.

Practical Use

The trim() method is commonly used to clean up user input fields:

<input type="text" id="search">
<script>
const inputValue = document.getElementById('search').value.trim();
</script>

Browser Support

All modern browsers fully support trim(), trimStart(), and trimEnd(), with the exception of Internet Explorer, which lacks support for these methods.

Alternative Approach

You can also use a regular expression to remove all spaces:

const string = ' hi ';
string.replace(/ /g, ''); // "hi"

Оцените статью