PowerShell TruncateAtWhitespace Function

PowerShell

Here’s a TruncateAtWhitespace function that takes an incoming parameter value and an incoming max length, and returns a substring broken at a whitespace position.  This way if you have “Lance has a blog” and you need to truncate it to 8 characters or less, you get “Lance…” instead of “Lance ha”.

PowerShell
function TruncateAtWhitespace{
    param(
        [string]$value,
        [int]$maxlength=200
    )
    $maxlength-=3; #allow for "..." suffix
    if ($value.Length -le $maxlength) {
      return ($value + "...");
    }
    $closestwhitespaceindex = [int]$value.Substring(0, $maxlength).LastIndexOf(" ");
    if ($closestwhitespaceindex -gt 0) {
      $value = $value.Substring(0, $closestwhitespaceindex) + "...";
    } else {
      $value = $value.Substring(0, $maxlength);
    }
    return $value;
}
PowerShell

Leave a Reply

Your email address will not be published. Required fields are marked *