Replace operator with one parameter

Welcome Forums General PowerShell Q&A Replace operator with one parameter

This topic contains 3 replies, has 3 voices, and was last updated by

js
 
Participant
3 months, 1 week ago.

  • Author
    Posts
  • #114168

    Participant
    Points: 23
    Rank: Member

    I found this bit of code which removes the last character of a string:

    $string -replace '.$'

    However the about_comparison_operators clearly states that replace takes two parameters. There is obviously an undocumented feature where the second parameter defaults to ""?

    If so, why wasnt it included in the official MS doco? Or is it documented somewhere else?

  • #114175
    js

    Participant
    Points: 452
    Helping Hand
    Rank: Contributor

    Maybe someone -replace'd it out of existence.

  • #114205

    Participant
    Points: 345
    Helping Hand
    Rank: Contributor

    The about_ page is a little ambiguous, in my opinion.

    The substitute argument is optional, and if left blank, will just remove the matched string.

  • #114226
    js

    Participant
    Points: 452
    Helping Hand
    Rank: Contributor

    Yep, it's the same as having a 2nd arg as empty string or null.

    PS C:\users\js> 'sosososo' -replace 's',$null
    oooo
    

    A lot of the operators work on arrays as well.

    PS C:\users\js> 'sosososo','sasasasa','sesesese' -replace 's'
    oooo
    aaaa
    eeee
    

The topic ‘Replace operator with one parameter’ is closed to new replies.