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
4 weeks, 1 day ago.

  • Author
    Posts
  • #114168

    Participant
    Points: 21
    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: 207
    Helping Hand
    Rank: Participant

    Maybe someone -replace'd it out of existence.

  • #114205

    Participant
    Points: 112
    Rank: Participant

    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: 207
    Helping Hand
    Rank: Participant

    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
    

You must be logged in to reply to this topic.