go.charczuk.com@v0.0.0-20240327042549-bc490516bd1a/projects/blogctl/pkg/engine/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 engine
     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  }