JavaScript
Coding Tutorial
String Manipulation
Web Development
Programming Tips

How to remove spaces from a string using JavaScript?

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

Introduction

Removing spaces from a JavaScript string sounds simple, but there are several different cases hiding behind that phrase. Sometimes you only want to trim leading and trailing whitespace, sometimes you want to remove literal space characters from the middle, and sometimes you want to remove every whitespace character including tabs and line breaks. Choosing the right method matters because each one changes the string in a different way.

Remove Only Leading and Trailing Whitespace

If the goal is to clean up user input without changing the text inside the value, use trim().

javascript
1const input = "   hello world   ";
2const cleaned = input.trim();
3
4console.log(cleaned); // "hello world"

trim() removes whitespace from the start and end of the string only. It does not touch the space between hello and world.

This is the right choice for form fields, search boxes, and query parameters where accidental outer whitespace should be ignored but internal spacing is still meaningful.

Remove Literal Space Characters Everywhere

If you want to remove actual space characters from the whole string, use replaceAll(" ", "") or replace(/ /g, "").

javascript
1const value = "12 34 56";
2const compact = value.replaceAll(" ", "");
3
4console.log(compact); // "123456"

This removes only the normal space character. Tabs, newlines, and other whitespace characters are left untouched.

That distinction is important. If your input may come from pasted text or formatted content, a plain space replacement is often too narrow.

Remove All Whitespace with a Regular Expression

To remove spaces, tabs, and line breaks, use a regular expression with \s.

javascript
1const text = "first line \n second\tline";
2const withoutWhitespace = text.replace(/\s+/g, "");
3
4console.log(withoutWhitespace); // "firstlinesecondline"

Here is what the pattern means:

  • '\s matches a whitespace character'
  • '+ matches one or more in a row'
  • 'g applies the replacement globally'

This is the most common solution when you truly want a compact string with no whitespace at all.

Normalize Instead of Fully Removing

Sometimes the real requirement is not "remove spaces" but "collapse messy whitespace into single spaces." That keeps text readable while still cleaning it up.

javascript
1const sentence = "JavaScript   makes \n string\tcleanup easier";
2const normalized = sentence.trim().replace(/\s+/g, " ");
3
4console.log(normalized); // "JavaScript makes string cleanup easier"

This pattern is useful for search indexing, display text, and content pasted from rich editors.

Strings Are Immutable

JavaScript strings do not change in place. Every operation returns a new string, so you must store the result.

javascript
1let name = "A B C";
2name.replace(/ /g, "");
3
4console.log(name); // still "A B C"
5
6name = name.replace(/ /g, "");
7console.log(name); // "ABC"

This catches a lot of people because the code looks correct at first glance. If you do not assign the result, nothing changes.

Choosing the Right Method

Use trim() when you want to clean the edges only.

Use replaceAll(" ", "") when you want to remove ordinary spaces and keep other whitespace intact.

Use replace(/\s+/g, "") when you want to remove all whitespace characters.

Use trim().replace(/\s+/g, " ") when you want readable normalized text instead of a fully compact string.

Those four patterns cover most real-world cases. The main mistake is choosing the strongest one by default and accidentally destroying intended formatting.

Common Pitfalls

The biggest pitfall is confusing spaces with whitespace. A string may contain tabs or newlines even when it looks like it only has spaces. If replaceAll(" ", "") seems to miss some characters, the input probably contains other whitespace.

Another common mistake is forgetting that trim() only affects the beginning and end of the string. It does not remove inner spaces.

Some developers also forget that replace() without a global regular expression only changes the first match:

javascript
const value = "a b c";
console.log(value.replace(" ", "")); // "ab c"

If you need every match, use replaceAll or a regex with the g flag.

Finally, be careful when removing whitespace from natural language text. "New York" and "NewYork" are not equivalent values. In many applications, collapsing multiple spaces is safer than removing them entirely.

Summary

  • 'trim() removes whitespace only from the start and end of a string.'
  • 'replaceAll(" ", "") removes literal space characters everywhere.'
  • 'replace(/\s+/g, "") removes all whitespace, including tabs and newlines.'
  • JavaScript strings are immutable, so store the returned value.
  • Normalize whitespace when readability matters more than creating a compact token.

Related reading
Free course
Beginner
7 lessons
2 hours
Tackling System Design Interview Problems

A short course that equips you with the skills to approach system design interviews methodically.

Start the free course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

All Rights Reserved.