Trim, TrimStart, and TrimEnd

The Trim method, by default, removes all white space (spaces, tabs, and line breaks) from the beginning and end of a string. For example:

$string = " 
    This string has leading and trailing white space      " 
$string.Trim() 

The TrimStart and TrimEnd methods limit their operation to either the start or end of the string.

Each of the methods accepts a list of characters to trim. For example:

$string = '*__This string is surrounded by clutter.--#' 
$string.Trim('*_-#') 

The Trim method does not remove a string from the end of another. The string supplied in the previous example ('*_-#') is treated as an array. This can be seen in the definition of the method:

PS> 'string'.Trim

OverloadDefinitions
-------------------
string Trim(Params char[] trimChars)
string Trim()

A failure to appreciate this can lead to unexpected behavior. The domain name in the following example ends with the suffix '.uk.net', the goal is to trim the suffix from the end of the string:

$string = 'magnet.uk.net' 
$string.TrimEnd('.uk.net')

As '.uk.net' is treated as an array of characters, the result of this expression is shorter than may be expected if the argument were a string:

PS> $string = 'magnet.uk.net'
$string.Trim('.uk.net')

mag
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.188.10.1