Removing Text from Strings

by Nov 10, 2017

Occasionally, you might read about Trim(), TrimStart(), and TrimEnd() to remove text from strings. And this seems to really work well:

 PS C:\> $testvalue = "this is strange" PS C:\> $testvalue.TrimEnd("strange") this is PS C:\> 

But what about this?

 PS C:\> $testvalue = "this is strange" PS C:\> $testvalue.TrimEnd(" strange") this i PS C:\> 

The truth is that Trim() methods treat your argument as a list of characters. Any of these characters are removed.

If you just want to remove text from a string anywhere, use Replace() instead:

 PS C:\> $testvalue.Replace(" strange", "") this is PS C:\> 

If you want more control, use regular expressions and anchors. To remove text from the end of a string only, the below code would do the trick. Only the word “strange” that ends the string would be removed.

$testvalue = "this is strange strange strange" $searchText = [Regex]::Escape("strange") $anchorTextEnd = "$" $pattern = "$searchText$anchorTextEnd" $testvalue -replace $pattern 

Twitter This Tip! ReTweet this Tip!