Skip to content

strings: fix Title function #21442

@GwynethLlewelyn

Description

@GwynethLlewelyn

First of all: no, this is not #6801!

Instead, I just wanted to point out that the current strings.Title() implementation is a 'quick & dirty' way of dealing with titles; it does not respect proper English rules for title naming (although it might be appropriate for some languages, I don't know).

A suggestion was made on the Go Cookbook to implement it thusly:

func properTitle(input string) string {
	words := strings.Fields(input)
	smallwords := " a an on the to "

	for index, word := range words {
		if strings.Contains(smallwords, " "+word+" ") {
			words[index] = word
		} else {
			words[index] = strings.Title(word)
		}
	}
	return strings.Join(words, " ")
}

This is a clever and neat trick, and could be used for other languages as well (ex. in Portuguese the smallwords would have to include " de do da dos das " but possibly exclude "a" since that is by coincidence also a definite article, etc.).
The authors of the Go Cookbook did not seem to add a suggestion here, so I'm doing it 🙂

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions