#PSTip Inserting characters at a specified string index position

How do you turn ‘20130701’ to ‘2013-07-01’?

There are many ways to tackle this, breaking it into pieces (substring) and joining it back with a dash, use some regex fu to manipulate it, parse it as a DateTime and format it and so on. Here’s another way that uses the String.Insert method.

The Insert() method takes two arguments–the index position of the insertion and the string to insert.

PS> "".Insert.OverloadDefinitions
string Insert(int startIndex, string value)

In our example we need to add a dash after the year part which is the fourth character.

PS> $s = '20130701'
PS> $s = $s.Insert(4,'-')
PS> $s

Now we can add the second dash right after the month/day part (depending on your culture):

PS> $s = $s.Insert(7,'-')
PS> $s

Or we can insert the dashes in two consecutive method calls:

PS> '20130701'.Insert(4,'-').Insert(7,'-')

About the author: Shay Levy

Shay Levy is a Co-founder and editor of the PowerShell Magazine. He is a multiple-year recipient of the Microsoft MVP award, and a Microsoft Certified Trainer (MCT). Shay often covers PowerShell related topics on his blog and you can also follow him on Twitter at @ShayLevy

Related Posts