PowerShell: How to Remove First and Last Characters from String


You can use the following syntax in PowerShell to remove the first and last characters from a string:

$my_string = $my_string -replace "^." -replace ".$"

This particular example removes the first character and the last character from the string stored in the variable named $my_string.

Note that we use the first -replace operator to match the first ( ^. ) character in the string and replace it with nothing.

Then we use the second -replace operator to match the last ( .$ ) character in the string and replace it with nothing.

This has the effect of removing both the first and last character from the string.

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

Example: Remove First and Last Characters from String in PowerShell

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

  • Sacramento

We can use the following syntax to remove both the first and last letter of this string:

$my_string = "Sacramento"
$my_string = $my_string -replace "^." -replace ".$"

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

Notice that this returns the following string:

  • acrament

Notice that the first and last character in the string have both been removed.

It’s also worth noting that you can use curly brackets { } to remove n characters from either the beginning or end of the string.

For example, you can use the following syntax to remove the first character from the string and the last three characters from the string:

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

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

PowerShell remove first character and last n characters

Notice that the first character and the last three characters have been removed from the string.

Feel free to use the curly brackets to remove any number of characters that you’d like from the beginning or end of a string.

Related Tutorials

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

PowerShell: How to Trim First N Characters from String
PowerShell: How to Count Specific Characters in String
PowerShell: How to Replace Special Characters in String

Leave a Reply