github.com/zhongdalu/gf@v1.0.0/g/text/gstr/gstr_trim.go (about)

     1  // Copyright 2019 gf Author(https://github.com/zhongdalu/gf). All Rights Reserved.
     2  //
     3  // This Source Code Form is subject to the terms of the MIT License.
     4  // If a copy of the MIT was not distributed with this file,
     5  // You can obtain one at https://github.com/zhongdalu/gf.
     6  
     7  package gstr
     8  
     9  import "strings"
    10  
    11  // Trim strips whitespace (or other characters) from the beginning and end of a string.
    12  func Trim(str string, characterMask ...string) string {
    13  	if len(characterMask) > 0 {
    14  		return strings.Trim(str, characterMask[0])
    15  	} else {
    16  		return strings.TrimSpace(str)
    17  	}
    18  }
    19  
    20  // TrimLeft strips whitespace (or other characters) from the beginning of a string.
    21  func TrimLeft(str string, characterMask ...string) string {
    22  	mask := ""
    23  	if len(characterMask) == 0 {
    24  		mask = string([]byte{'\t', '\n', '\v', '\f', '\r', ' ', 0x85, 0xA0})
    25  	} else {
    26  		mask = characterMask[0]
    27  	}
    28  	return strings.TrimLeft(str, mask)
    29  }
    30  
    31  // TrimLeftStr strips all of the given <cut> string from the beginning of a string.
    32  func TrimLeftStr(str string, cut string) string {
    33  	for str[0:len(cut)] == cut {
    34  		str = str[len(cut):]
    35  	}
    36  	return str
    37  }
    38  
    39  // TrimRight strips whitespace (or other characters) from the end of a string.
    40  func TrimRight(str string, characterMask ...string) string {
    41  	mask := ""
    42  	if len(characterMask) == 0 {
    43  		mask = string([]byte{'\t', '\n', '\v', '\f', '\r', ' ', 0x85, 0xA0})
    44  	} else {
    45  		mask = characterMask[0]
    46  	}
    47  	return strings.TrimRight(str, mask)
    48  }
    49  
    50  // TrimRightStr strips all of the given <cut> string from the end of a string.
    51  func TrimRightStr(str string, cut string) string {
    52  	for {
    53  		length := len(str)
    54  		if str[length-len(cut):length] == cut {
    55  			str = str[:length-len(cut)]
    56  		} else {
    57  			break
    58  		}
    59  	}
    60  	return str
    61  }