Drill

ProblemsGo › text

Turn a product title into a URL slug

mediumtextStringsParsingGo

The catalogue builds a URL from each product title, and the result has to be safe to put in a path.

slugify(title: string) → string

Go needs a compiler and Drill does not host one yet, so this page is the reference rather than an exercise: the problem, worked examples, and the solution in full. To type it out, the same problem runs in Python.

Solve it in Python →

Where you start

func slugify(title string) string {
	
}

Worked examples

CallResult
slugify(" Blue Widget, 12mm! ")"blue-widget-12mm"
slugify("A---B")"a-b"
slugify("Already-slugged")"already-slugged"
slugify("!!!")""

Hint

Append a dash only when there is already something to separate, then trim the one you may have left on the end.

Reference solution in Go
func slugify(title string) string {
	result := []byte{}
	lower := strings.ToLower(title)
	for i := 0; i < len(lower); i++ {
		ch := lower[i]
		if (ch >= 'a' && ch <= 'z') || (ch >= '0' && ch <= '9') {
			result = append(result, ch)
		} else if len(result) > 0 && result[len(result)-1] != '-' {
			result = append(result, '-')
		}
	}
	if len(result) > 0 && result[len(result)-1] == '-' {
		result = result[:len(result)-1]
	}
	return string(result)
}

The same problem in another language

More text problems in Go