3

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

2 Answers 2

2

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
Sign up to request clarification or add additional context in comments.

Comments

1

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'

2 Comments

Thanks jisaak. Great info. What i mean is i want to use this format $myname = $firstname + " " + $lastname. But when i use the Length function as below, it will include to count the space as well. How to not include the space when using the length function as below $myname.Length
Can you provide an example with the firstname and lastname and the desired output?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.