Search code examples
powershelltrim

Using .trimend() in PowerShell


I am really new to PowerShell. I am trying to use .TrimEnd(", ").

How do I have it trim the end only if the characters ", " exist at the end? And to skip otherwise?

I have looked online, but I could not find any information.


Solution

  • TrimEnd and the other trim methods from the String class will remove any appearance of any of the characters passed as argument so in this case, these methods will not solve your issue. You could definitely use -replace in this case and by doing so there wouldn't be a need to check if the string ends with , just let the regex replacement operator handle that for you.

    'string, ' -replace ', $'
    

    See https://regex101.com/r/cLCgC3/1 for details and a more visualized representation of what this means.