go.charczuk.com@v0.0.0-20240327042549-bc490516bd1a/sdk/stringutil/slugify.go (about)

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