Cookies management by TermsFeed Cookie Consent

🥇 How to uppercase the first letter of each word in Go

shorts strings

Please consider supporting us by disabling your ad blocker

If you want to make a title from your string in Go, i.e., make the first letter of each word in the string uppercase, you need to use the cases.Title() function from the golang.org/x/text/cases package. The function creates a language-specific title caser that capitalizes the first letter of each word.

Also check out how to convert an entire string to uppercase here.

Look at the example below. We create a new generic title caser using undefined language language.Und. If you are sure that your strings are in a specific language, you can set it, for example, language.English, language.German, etc. Next, we transform the string using the created caser with the Caser.String() method. The result is a string where the first letter of each word is capitalized, and the remaining letters are lowercase.

package main

import (
    "fmt"

    "golang.org/x/text/cases"
    "golang.org/x/text/language"
)

func main() {
    fmt.Println(cases.Title(language.Und).String("goSAMples.dev is the best Go bLog in the world!"))
}

Output:

Gosamples.dev Is The Best Go Blog In The World!

If you want to disable the lowercasing of non-leading letters, use the cases.NoLower option as the second parameter of the cases.Title() function.

package main

import (
    "fmt"

    "golang.org/x/text/cases"
    "golang.org/x/text/language"
)

func main() {
    fmt.Println(cases.Title(language.Und, cases.NoLower).String("goSAMples.dev is the best Go bLog in the world!"))
}

Output:

GoSAMples.dev Is The Best Go BLog In The World!

Thank you for being on our site 😊. If you like our tutorials and examples, please consider supporting us with a cup of coffee and we'll turn it into more great Go examples.

Have a great day!

🐾 How to compare strings in Go

shorts introduction strings

🔁 Repeat a string in Go

shorts strings

🔠 String to uppercase in Go

shorts strings