github.com/richardwilkes/toolbox@v1.121.0/txt/substr.go (about)

     1  // Copyright (c) 2016-2024 by Richard A. Wilkes. All rights reserved.
     2  //
     3  // This Source Code Form is subject to the terms of the Mozilla Public
     4  // License, version 2.0. If a copy of the MPL was not distributed with
     5  // this file, You can obtain one at http://mozilla.org/MPL/2.0/.
     6  //
     7  // This Source Code Form is "Incompatible With Secondary Licenses", as
     8  // defined by the Mozilla Public License, version 2.0.
     9  
    10  package txt
    11  
    12  // FirstN returns the first n runes of a string.
    13  func FirstN(s string, n int) string {
    14  	if n < 1 {
    15  		return ""
    16  	}
    17  	r := []rune(s)
    18  	if n > len(r) {
    19  		return s
    20  	}
    21  	return string(r[:n])
    22  }
    23  
    24  // LastN returns the last n runes of a string.
    25  func LastN(s string, n int) string {
    26  	if n < 1 {
    27  		return ""
    28  	}
    29  	r := []rune(s)
    30  	if n > len(r) {
    31  		return s
    32  	}
    33  	return string(r[len(r)-n:])
    34  }
    35  
    36  // Truncate the input string to count runes, trimming from the end if keepFirst is true or the start if not. If trimming
    37  // occurs, a … will be added in place of the trimmed characters.
    38  func Truncate(s string, count int, keepFirst bool) string {
    39  	var result string
    40  	if keepFirst {
    41  		result = FirstN(s, count)
    42  	} else {
    43  		result = LastN(s, count)
    44  	}
    45  	if result != s {
    46  		if keepFirst {
    47  			result += "…"
    48  		} else {
    49  			result = "…" + result
    50  		}
    51  	}
    52  	return result
    53  }