0
0
JavascriptProgramBeginner · 2 min read

JavaScript Program to Remove Whitespace from String

You can remove all whitespace from a string in JavaScript using str.replace(/\s+/g, ''), which replaces all spaces, tabs, and newlines with nothing.
📋

Examples

Inputhello world
Outputhelloworld
Input JavaScript is fun
OutputJavaScriptisfun
Input spaced text
Outputspacedtext
🧠

How to Think About It

To remove whitespace from a string, think about finding all spaces, tabs, and newlines and then deleting them. We can do this by searching for any whitespace character and replacing it with nothing, effectively removing it.
📐

Algorithm

1
Get the input string.
2
Find all whitespace characters in the string.
3
Replace each whitespace character with an empty string.
4
Return the cleaned string without any whitespace.
💻

Code

javascript
function removeWhitespace(str) {
  return str.replace(/\s+/g, '');
}

const input = "  Hello  World \t";
const output = removeWhitespace(input);
console.log(output);
Output
HelloWorld
🔍

Dry Run

Let's trace the input string " Hello World \t" through the code.

1

Input string

" Hello World \t"

2

Apply replace with regex /\s+/g

All spaces and tab characters matched: " ", " ", " \t"

3

Replace all matched whitespace with ''

Resulting string: "HelloWorld"

Original StringWhitespace FoundResult After Replacement
Hello World spaces and tabHelloWorld
💡

Why This Works

Step 1: Use of regex \s

The \s pattern matches any whitespace character like spaces, tabs, and newlines.

Step 2: Global flag g

The g flag makes sure all whitespace occurrences in the string are replaced, not just the first one.

Step 3: Replacing with empty string

Replacing matched whitespace with '' removes them completely from the string.

🔄

Alternative Approaches

Using split and join
javascript
function removeWhitespace(str) {
  return str.split(/\s+/).join('');
}

console.log(removeWhitespace(' a b c '));
This splits the string by whitespace and joins parts without spaces; slightly less direct but easy to understand.
Using loop and manual check
javascript
function removeWhitespace(str) {
  let result = '';
  for (const char of str) {
    if (char !== ' ' && char !== '\t' && char !== '\n') {
      result += char;
    }
  }
  return result;
}

console.log(removeWhitespace(' a b c '));
Manually checks each character; more code but good for learning how to filter characters.

Complexity: O(n) time, O(n) space

Time Complexity

The program scans each character once to find whitespace, so it runs in linear time relative to string length.

Space Complexity

A new string is created without whitespace, so space used is proportional to the input size.

Which Approach is Fastest?

Using replace with regex is usually fastest and most concise compared to splitting or manual loops.

ApproachTimeSpaceBest For
Regex replaceO(n)O(n)Quick and concise removal of all whitespace
Split and joinO(n)O(n)Readable alternative, good for beginners
Manual loopO(n)O(n)Learning character filtering, less concise
💡
Use the regex /\s+/g with replace to remove all whitespace quickly.
⚠️
Forgetting the global g flag causes only the first whitespace to be removed.