PowerShell: How to Remove Spaces from String


You can use the following syntax in PowerShell to remove all spaces from a string:

$my_string = $my_string -replace '\s',''

This particular example removes all spaces in the string variable named $my_string.

Note that this syntax uses -replace to replace one pattern with another pattern in a string.

In this example, we use \s to match all spaces in the string and we specify that nothing should be used as a replacement, which allows us to simply remove all spaces from the string.

The following examples show how to use each method in practice.

Example: How to Remove Spaces from String in PowerShell

Suppose that we create the following string variable named $my_string in PowerShell:

$my_string = 'The Mavs are my favorite team'

We can use the following syntax to remove all spaces from this string:

$my_string = $my_string -replace '\s',''

The following example shows how to use this syntax in practice:

PowerShell remove spaces from string

Notice that all spaces have been removed from the string.

Note: It’s necessary to assign the results of the -replace operator back to the original string variable because -replace does not modify a string in-place.

Related Tutorials

The following tutorials explain how to perform other common tasks in PowerShell:

PowerShell: How to Get Last Item in Array
PowerShell: How to List Files in Directory by Date
PowerShell: How to List All Files in Directory to Text File

Leave a Reply