Johan
Johan

Reputation: 307

How to remove space when combining variables in PowerShell

Would like to know how to remove space when combining string variables in below code. Cause when I count the length of $myname, it will also include the space length

$myname = $firstname + " " + $lastname

Upvotes: 3

Views: 4516

Answers (2)

Diabetic4Life
Diabetic4Life

Reputation: 36

Use replace and regex to replace spaces with nothing before you do the length function. Last $myname is just to prove we didn't actually remove spaces in the variable while getting the length.

$LastName = "Smith"
$FirstName = "John"
$myname = $Firstname + " " + $Lastname
$myname
($myname -replace "\s","").length
$myname

Output

John Smith
9
John Smith

Upvotes: 2

Martin Brandl
Martin Brandl

Reputation: 58931

If you want to combine the two variables without space between, just use

$myname = $firstname  + $lastname

Or a format string:

$myname = '{0}{1}' -f $firstname, $lastname

If you want to remove the spaces at the start and end, use

$myname = ('{0}{1}' -f $firstname, $lastname).Trim()

You could also use TrimEnd to only trim the spaces at the end of the string or TrimStart to only trim the spaces at the start. If you want to get rid of all spaces in the string, you could use a regex:

$myname = ('{0}{1}' -f $firstname, $lastname) -replace '\s'

Upvotes: 1

Related Questions