0
0
PowershellHow-ToBeginner · 2 min read

PowerShell Script to Remove Spaces from String

Use the PowerShell command $string -replace ' ', '' to remove all spaces from a string.
📋

Examples

Inputhello world
Outputhelloworld
Input PowerShell script
OutputPowerShellscript
InputnoSpacesHere
OutputnoSpacesHere
🧠

How to Think About It

To remove spaces from a string, think of replacing every space character with nothing. This means scanning the string and deleting all spaces wherever they appear.
📐

Algorithm

1
Get the input string.
2
Find all space characters in the string.
3
Replace each space with an empty string.
4
Return the modified string without spaces.
💻

Code

powershell
$string = "PowerShell script to remove spaces"
$result = $string -replace ' ', ''
Write-Output $result
Output
PowerShellscripttoremovespaces
🔍

Dry Run

Let's trace the string 'hello world' through the code

1

Input string

hello world

2

Replace spaces

Remove all ' ' characters

3

Output string

helloworld

StepString Value
Initialhello world
After replacehelloworld
💡

Why This Works

Step 1: Using -replace operator

The -replace operator in PowerShell replaces text matching a pattern with a new string.

Step 2: Pattern is space character

We specify a single space ' ' as the pattern to find all spaces.

Step 3: Replace with empty string

Replacing spaces with '' removes them from the string.

🔄

Alternative Approaches

Using .Replace() method
powershell
$string = "PowerShell script to remove spaces"
$result = $string.Replace(' ', '')
Write-Output $result
This method is simple and fast but only replaces literal spaces, not other whitespace.
Using regex to remove all whitespace
powershell
$string = "PowerShell script to remove spaces"
$result = $string -replace '\s', ''
Write-Output $result
This removes all whitespace characters including tabs and newlines, not just spaces.

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

Time Complexity

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

Space Complexity

A new string is created without spaces, so space usage is proportional to the input string size.

Which Approach is Fastest?

Using .Replace() is slightly faster for simple space removal, but -replace is more flexible for patterns.

ApproachTimeSpaceBest For
-replace ' 'O(n)O(n)Removing spaces with regex flexibility
.Replace(' ')O(n)O(n)Simple literal space removal
-replace '\s'O(n)O(n)Removing all whitespace characters
💡
Use -replace ' ', '' to quickly remove all spaces from a string in PowerShell.
⚠️
Beginners often forget that -replace uses regex patterns, so escaping special characters is important.