TrimEnd with a string not doing what you expect!
TrimEnd with a string trimming more than you expected with PowerShell? Find out why.
January 20, 2017
Q. The TrimEnd string function is removing more characters than I'm specifying, why?
A. If I use to use the command below what would the expected output be?
"johnsavilllife".TrimEnd("life")
It says to remove the word life from the end so it should result in johnsavill. Lets try it:
PS C:> "johnsavilllife".TrimEnd("life")
johnsav
Where did the ill from the end of Savill go? The problem is TrimEnd is not doing what we think it's doing. It is not removing the word from the end of the string, its removing any of the characters from the end of the string, i.e. l i f and e. The problem is Savill ends with i and l so those characters are removed as well. If you want to remove only a set word a better option is to trim a number of characters, in this case 4, e.g.
PS C:> $tststring = "johnsavilllife"
PS C:> $tststring.Substring(0,(($tststring.Length)-4))
johnsavill
About the Author
You May Also Like