github.com/blend/go-sdk@v1.20220411.3/stringutil/slugify.go (about)

     1  /*
     2  
     3  Copyright (c) 2022 - Present. Blend Labs, Inc. All rights reserved
     4  Use of this source code is governed by a MIT license that can be found in the LICENSE file.
     5  
     6  */
     7  
     8  package stringutil
     9  
    10  import (
    11  	"unicode"
    12  )
    13  
    14  // Slugify replaces non-letter or digit runes with '-'.
    15  // It will not add repeated '-'.
    16  func Slugify(v string) string {
    17  	runes := []rune(v)
    18  
    19  	var output []rune
    20  	var c rune
    21  	var lastWasDash bool
    22  
    23  	for index := range runes {
    24  		c = runes[index]
    25  		// add letters and make them lowercase
    26  		if unicode.IsLetter(c) {
    27  			output = append(output, unicode.ToLower(c))
    28  			lastWasDash = false
    29  			continue
    30  		}
    31  		// add digits unchanged
    32  		if unicode.IsDigit(c) {
    33  			output = append(output, c)
    34  			lastWasDash = false
    35  			continue
    36  		}
    37  		// if we hit a dash, only add it if
    38  		// the last character wasnt a dash
    39  		if c == '-' {
    40  			if !lastWasDash {
    41  				output = append(output, c)
    42  				lastWasDash = true
    43  			}
    44  			continue
    45  
    46  		}
    47  		if unicode.IsSpace(c) {
    48  			if !lastWasDash {
    49  				output = append(output, '-')
    50  				lastWasDash = true
    51  			}
    52  			continue
    53  		}
    54  	}
    55  	return string(output)
    56  }