Use the PowerShell String replace()
method or replace
operator to replace the space in a string with a new line. e.g. $str.replace(" ","`r`n")
replace the space with a new line.
The replace() method returns a string where all space is replaced by a new line. In PowerShell, to add a new line, it uses `r`n
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 New Line 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 new line $str.Replace(" ","`r`n")
The above PowerShell script uses the replace()
method to replace space in a string with new line
PowerShell replace()
method takes 2 arguments:
- the substring to search for in the given string
- the replacement string for the found text
The PowerShell replace() method returns a new string where all the space in a string is replaced by the new line.
The output of the above script to replace all space with a new line is:
Cool Tip: How to replace the first occurrence of a string in PowerShell!
Use replace Operator to Replace Space with Newline in PowerShell
Using the PowerShell replace operator
, you can replace all space in a string with a new line.
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 new line $str -replace ' ', "`r`n"
The above PowerShell script uses the replace operator to replace space in a string with a new line. It uses `r`n to add a new line.
replace operator takes 2 arguments:
- the substring to search for in a string
- the replacement string
In the first example, replace
operator replaces all space with a new line.
The output of the above Powershell script to replace space in a string is:
PS C:\> $str = "C# PowerShell NodeJs"
PS C:\> $str -replace ' ', "`r`n"
C#
PowerShell
NodeJs
Cool Tip: How to replace all single quotes in a string using PowerShell!
Conclusion
I hope the above article on how to replace all space with a new line 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.