Use the PowerShell String replace()
method or replace
operator to replace the space in a string with a comma. e.g. $str.replace(" ",",")
replace the space with a comma.
The replace() method returns a string where all space is replaced by a comma.
In this article, we will discuss how to use PowerShell replace() method or replace operator to replace space in a string.
Use replace() to Replace Space with Comma in PowerShell
PowerShell String built-in replace() method takes two arguments; a string to search and a string to replace with the found text.
$str = "C# PowerShell NodeJs" # Replace all space with a comma $str.Replace(" ",",")
The above PowerShell script uses the replace()
method to replace space in a string with a comma
PowerShell replace()
function takes 2 arguments:
- the substring to search for in the given string, in the above example, space
- the replacement string for the found text, in the above example, comma,
The PowerShell replace() method returns a new string where all the space in a string is replaced by the comma.
The output of the above script to replace all space with a comma is:
Cool Tip: How to replace the first occurrence of a string in PowerShell!
Use replace Operator to Replace Space with Comma in PowerShell
Using the PowerShell replace operator, you can replace all space in a string with a comma.
The replace operator in PowerShell takes two arguments; string to find for in a string and replacement string for the found text.
$str = "C# PowerShell NodeJs" # Replace all space with comma $str -replace ' ', ","
The above PowerShell script uses the replace operator to replace space in a string with a comma.
replace operator takes 2 arguments:
- the substring to search for in a string
- the replacement string
In the first example, replace
operator replaces all spaces with a comma.
The output of the above Powershell script to replace space in a string is:
PS C:\> $str = "C# PowerShell NodeJs"
PS C:\> $str -replace ' ', ","
C#,PowerShell,NodeJs
Cool Tip: How to do case insensitive replacement in a string using PowerShell!
Conclusion
I hope the above article on how to replace all space with a comma in a string using PowerShell replace() method is helpful to you.
You can find more topics about PowerShell Active Directory commands and PowerShell basics on the ShellGeek home page.