PowerShell: How to Remove Last Character from String


You can use the following methods in PowerShell to remove the last character from a string:

Method 1: Remove Last Character from String

$my_string = $my_string -replace ".$"

This particular example removes the last character in the string variable named $my_string.

Method 2: Remove Last N Characters from String

$my_string = $my_string -replace ".{3}$" 

This particular example removes the last 3 characters in the string variable named $my_string.

Note that both of these methods use -replace along with .$ to match the last character in a string and replace it with nothing, which allows us to remove the last character in the string.

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

Example 1: Remove Last Character from String in PowerShell

We can use the following syntax to remove the last character of a string variable in PowerShell:

$my_string = "The Mavs are my favorite team"
$my_string = $my_string -replace ".$"

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

PowerShell remove last character from string

Notice that the last character in the string has been removed.

Example 2: Remove Last N Characters from String in PowerShell

We can use the following syntax to remove the last three characters of a string variable in PowerShell:

$my_string = "The Mavs are my favorite team"
$my_string = $my_string -replace ".{3}$"

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

PowerShell remove last N characters from string

Notice that the last three characters in the string have been removed.

Note: Feel free to replace the 3 in the code with a different number to instead remove a different number of characters from the end of a string.

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