github.com/starshine-sys/bcr@v0.21.0/strings.go (about)

     1  package bcr
     2  
     3  import (
     4  	"fmt"
     5  	"strings"
     6  )
     7  
     8  // TrimPrefixesSpace trims all given prefixes as well as whitespace from the given string
     9  func TrimPrefixesSpace(s string, prefixes ...string) string {
    10  	for _, prefix := range prefixes {
    11  		s = strings.TrimPrefix(s, prefix)
    12  	}
    13  	s = strings.TrimSpace(s)
    14  	return s
    15  }
    16  
    17  // HasAnyPrefix checks if the string has *any* of the given prefixes
    18  func HasAnyPrefix(s string, prefixes ...string) bool {
    19  	for _, prefix := range prefixes {
    20  		if strings.HasPrefix(s, prefix) {
    21  			return true
    22  		}
    23  	}
    24  	return false
    25  }
    26  
    27  // HasAnySuffix checks if the string has *any* of the given suffixes
    28  func HasAnySuffix(s string, suffixes ...string) bool {
    29  	for _, suffix := range suffixes {
    30  		if strings.HasSuffix(s, suffix) {
    31  			return true
    32  		}
    33  	}
    34  	return false
    35  }
    36  
    37  // SprintfAll takes a slice of strings and uses them as input for Sprintf, returning a slice of strings
    38  func SprintfAll(template string, in []string) []string {
    39  	out := make([]string, 0)
    40  	for _, i := range in {
    41  		out = append(out, fmt.Sprintf(template, i))
    42  	}
    43  
    44  	return out
    45  }
    46  
    47  // EscapeBackticks escapes backticks in strings
    48  func EscapeBackticks(s string) string {
    49  	// Break all pairs of backticks by placing a ZWNBSP (U+FEFF) between them.
    50  	// Run twice to catch any pairs that are created from the first pass
    51  	s = strings.ReplaceAll(s, "``", "`\ufeff`")
    52  	s = strings.ReplaceAll(s, "``", "`\ufeff`")
    53  
    54  	// Escape the start/end of the string if necessary to better "connect" with other things
    55  	if strings.HasPrefix(s, "`") {
    56  		s = "\ufeff" + s
    57  	}
    58  	if strings.HasSuffix(s, "`") {
    59  		s = s + "\ufeff"
    60  	}
    61  
    62  	return s
    63  }
    64  
    65  // AsCode returns the given string as code, correctly escaped
    66  func AsCode(s string) string {
    67  	return "``" + EscapeBackticks(s) + "``"
    68  }
    69  
    70  // DefaultValue returns the second value if the first is empty
    71  func DefaultValue(s, def string) string {
    72  	if s != "" {
    73  		return s
    74  	}
    75  	return def
    76  }