TrimEnd with a string not doing what you expect!

TrimEnd with a string not doing what you expect!

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

Hide comments

Comments

  • Allowed HTML tags: <em> <strong> <blockquote> <br> <p>

Plain text

  • No HTML tags allowed.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Lines and paragraphs break automatically.
Publish