Home » PowerShell » PowerShell Replace First Character in String

PowerShell Replace First Character in String

Using the PowerShell replace operator with regex expression to find the first character in PowerShell, you can replace the first character in a string. Anchor ^ asserts the position of the start of the string is used in the regex expression.

In this article, we will discuss how to replace the first character in a string using PowerShell replace operator or replace() method.

PowerShell Replace First Character in String

Use the PowerShell replace operator to replace the first character in a string. Use the anchor ^ for the start of the string as the first argument in the replace operator and the second argument is to replace it with a new string.

Refer to the following code for the replacement of the first character.

$str = "Admin! Let's learn PowerShell with Hello World program."  

$str -replace '^(.)','SysA'  

In the above PowerShell script, the $str variable stores the string data.

Use replace operator over the string variable $str to search for a first character using anchor ^ and regex expression (.) and second argument SysA to replace with found the first character.

The output of the replacement of the first character in a string using the PowerShell replace operator is:

PowerShell replace first character in a string
PowerShell replace the first character in a string

Cool Tip: How to replace the first occurrence of a string in PowerShell!

Replace First Character in a String using PowerShell replace() method

Using the PowerShell string replace() method, you can find and replace the first character in a string. To get the first character in a string, use the substring method.

Convert the first character to [regex] type and use replace() method to replace the first character with the replacement string.

$test = "Admin! Let's learn PowerShell with Hello World program."

# Get the first character
$firsChar = $test.Substring(0,1)

# Convert the first character to regex type variable
[regex]$pattern = $firsChar

# use replace() method to replace the first character
$pattern.replace($test, "SysA") 

In the above PowerShell script, the $test variable stores the string data.

Using the PowerShell string substring() method, it gets the first character as A

Convert the character to regex type variable $pattern and use the replace() method to replace the first character with string SysA

The output of the above PowerShell script to replace the first character in a string is:

SysAdmin! Let's learn PowerShell with Hello World program.

Conclusion

I hope the above article on how to replace the first character using the PowerShell replace operator and replace() method is helpful to you.

You can find more topics about PowerShell Active Directory commands and PowerShell basics on the ShellGeek home page.