r/PowerShell • • Jan 20 '26

Solved Replacing the nth instance of a character?

Is there a way to replace say the 3rd space in a string to a dash?:

The quick brown fox jumped over the lazy dog
becomes
The quick brown**-**fox jumped over the lazy dog

I'm doing this with file names so the words differ, otherwise I would do:
$FileName = $FileName.Replace("brown fox","brown-fox")

Looking to avoid using split on space and then rejoining the text including the dash, or counting to the ~15th character etc. TIA

3 Upvotes

26 comments sorted by

View all comments

Show parent comment

2

u/Over_Dingo Jan 20 '26

exactly, would have to -split $string (which OP said he wants to avoid), or [char[]]$string