Strings and Numbers
Introduction
Laravel includes a variety of string helpers in the str package for common tasks like generating URL slugs, formatting field labels, and truncating previews. Its companion, the number package, formats counts, file sizes, and amounts of money for people to read. They're plain functions, so you may call them anywhere in your application, such as in handlers, mail, and commands:
1import (2 "go.laravel.com/number"3 "go.laravel.com/str"4)56slug := str.Slug("My First Post") // my-first-post7label := str.Headline("first_name") // First Name8table := str.Plural(str.Snake("BlogPost")) // blog_posts9preview := str.Limit("Thanks for the detailed write-up on queues", 20) // Thanks for the detai...10views := number.Abbreviate(1_250_000) // 1.3M1import (2 "go.laravel.com/number"3 "go.laravel.com/str"4)56slug := str.Slug("My First Post") // my-first-post7label := str.Headline("first_name") // First Name8table := str.Plural(str.Snake("BlogPost")) // blog_posts9preview := str.Limit("Thanks for the detailed write-up on queues", 20) // Thanks for the detai...10views := number.Abbreviate(1_250_000) // 1.3M
All lengths, positions, and widths count Unicode characters rather than bytes, so str.Take("这是一段中文", 2) returns "这是".
Every view can already call a few formatting functions, such as title and round. To use another function from this page in your views, such as str.Limit or number.Cents, check out the templates guide's section on functions of your own.
Available functions
The tables below list the functions in the str package, grouped by category.
Case
Use these functions to convert identifiers and titles between naming conventions:
| Function | Result |
|---|---|
str.Snake("BlogPost") |
blog_post |
str.Snake("UserID") |
user_id |
str.Kebab("BlogPost") |
blog-post |
str.Studly("blog_post") |
BlogPost |
str.Camel("blog_post") |
blogPost |
str.Title("a nice title uses the correct case") |
A Nice Title Uses The Correct Case |
str.Headline("EmailNotificationSent") |
Email Notification Sent |
str.UpperFirst("taylor otwell") |
Taylor otwell |
str.LowerFirst("Taylor") |
taylor |
str.SplitUpper("laravelFramework") |
["laravel" "Framework"] |
str.Slug("Hello World!") |
hello-world |
str.SlugWith("Hello World!", |
hello_world |
str.ASCII("Ünïcödé") |
Unicode |
Capitals in a row stay together as one word, so a Go field such as UserID becomes user_id. A slug keeps accented letters, so str.Slug("Café") is café. To drop the accents too, call str.ASCII first, as in str.Slug(str.ASCII("Café")).
For upper and lower case, use the standard library's strings.ToUpper and strings.ToLower.
Plurals
| Function | Result |
|---|---|
str.Plural("photo") |
photos |
str.Plural("category") |
categories |
str.Plural("child") |
children |
str.Plural("BlogPost") |
BlogPosts |
str.Singular("blog_posts") |
blog_post |
str.Singular("people") |
person |
str.Plural and str.Singular use English rules. In a name such as BlogPost, they change the last word and keep its case.
When you show how many of something there are, such as a post's comments, you may pass the count to str.Plural. It returns the word unchanged for a count of one and the plural for any other count, so you don't need an if for the singular:
1// 1 comment, or 3 comments2summary := fmt.Sprintf("%d %s", len(comments), str.Plural("comment", len(comments)))1// 1 comment, or 3 comments2summary := fmt.Sprintf("%d %s", len(comments), str.Plural("comment", len(comments)))
Substrings
These functions cut a string at a search string or a number of characters:
| Function | Result |
|---|---|
str.After("app/Http/Kernel", |
Http/Kernel |
str.AfterLast("app/Http/Kernel", |
Kernel |
str.Before("app/Http/Kernel", |
app |
str.BeforeLast("app/Http/Kernel", |
app/Http |
str.Between("[a] and [b]", |
a] and [b |
str.BetweenFirst("[a] and [b]", |
a |
str.Take("Build something amazing!", |
Build |
When the string doesn't contain the search, these functions return the whole string. If your code needs to know whether the search was there, such as when it reads an invoice number from a payment memo, use the standard library's strings.Cut, which also reports whether it found the search.
To remove a prefix or a suffix once, such as the https:// of a URL, use strings.TrimPrefix and strings.TrimSuffix.
Replacing
| Function | Result |
|---|---|
str.Start("this/string", |
/this/string |
str.Finish("this/string", |
this/string/ |
str.ReplaceLast("the fox the dog", |
the fox a dog |
str.ReplaceStart("Hello World", |
Laravel World |
str.ReplaceEnd("Hello World", |
Hello Laravel |
str.Swap("Tacos are great!", |
Burritos are fantastic! |
str.Start and str.Finish make sure the string starts or ends with exactly one copy of the prefix or suffix, so str.Start("//this/string", "/") is also /this/string. str.ReplaceStart and str.ReplaceEnd change the text only when the string starts or ends with the search. str.Swap replaces every key of the map in one pass, so a replacement is never replaced again.
To replace every match, use the standard library's strings.ReplaceAll. To replace only the first, use strings.Replace(s, search, replace, 1).
Shortening and wrapping
When you show a long post or comment in a list, you'll want a preview that fits. str.Limit cuts to a number of characters and str.Words cuts to a number of words:
| Function | Result |
|---|---|
str.Limit("The quick brown fox", |
The quick... |
str.LimitWith("The quick brown fox", |
The quick → |
str.Words("Perfectly balanced, |
Perfectly balanced, as... |
str.WordsWith("Perfectly balanced, |
Perfectly balanced, as >>> |
str.Excerpt("This is my name", |
"...is my na...", true |
str.WordWrap("The quick brown fox", |
The quick\nbrown fox |
str.WordCount("Hello world") |
2 |
str.Limit and str.Words add the ending only when they cut the string, and the ending doesn't count toward the limit. str.Excerpt returns the first match of the phrase, ignoring case, with up to that many characters on each side. It reports false when the phrase isn't there, so a search results page may fall back to a preview:
1excerpt, ok := str.Excerpt(post.Body, query, 40)2if !ok {3 excerpt = str.Limit(post.Body, 80)4}1excerpt, ok := str.Excerpt(post.Body, query, 40)2if !ok {3 excerpt = str.Limit(post.Body, 80)4}
Padding, masking, and cleaning
| Function | Result |
|---|---|
str.PadStart("42", |
00042 |
str.PadEnd("James", |
James----- |
str.PadBoth("James", |
__James___ |
str.Mask("[email protected]", |
tay*************** |
str.Mask("4242424242424242", |
************4242 |
str.Squish(" laravel framework ") |
laravel framework |
str.Deduplicate("/docs//strings///methods", |
/docs/strings/methods |
str.Digits("(555) 123-4567") |
5551234567 |
str.Mask masks from a character position to the end of the string. You may also pass a length, and a negative length leaves that many characters unmasked at the end, so to show only the last four digits of a card number, mask from 0 with a length of -4. A negative position counts back from the end. When the string is already as wide as the width you pass, the padding functions return it unchanged.
Matching
str.Resembles checks a string against a pattern in which * matches any characters, including none. The match is case-sensitive and must cover the whole string, which makes it useful for checking a path against a list of patterns:
1str.Resembles("posts/1/edit", "posts/*") // true2str.Resembles("posts/1/edit", "*/edit") // true3str.Resembles("posts", "posts/*") // false1str.Resembles("posts/1/edit", "posts/*") // true2str.Resembles("posts/1/edit", "*/edit") // true3str.Resembles("posts", "posts/*") // false
For a plain substring, prefix, or suffix, use the standard library's strings.Contains, strings.HasPrefix, and strings.HasSuffix. For more complex patterns, use the standard library's regexp package.
Random strings and identifiers
When generating invitation links, API tokens, or unique identifiers, use the functions in the str package, which draw from crypto/rand, the operating system's cryptographically secure random number generator:
1token := str.Random(40) // 40 letters and digits2password := str.Password(16) // letters, digits, and symbols3id := str.UUID() // a version 4 UUID4ordered := str.UUID7() // a version 7 UUID, which sorts by time5ulid := str.ULID() // a ULID, such as 01ARZ3NDEKTSV4RRFFQ69G5FAV1token := str.Random(40) // 40 letters and digits2password := str.Password(16) // letters, digits, and symbols3id := str.UUID() // a version 4 UUID4ordered := str.UUID7() // a version 7 UUID, which sorts by time5ulid := str.ULID() // a ULID, such as 01ARZ3NDEKTSV4RRFFQ69G5FAV
Because str.UUID7 and str.ULID embed a creation timestamp at the start, they sort chronologically and append cleanly to database indexes, making them a better choice for primary keys than random str.UUID values. Choose str.UUID7 for a uuid column, and str.ULID for a shorter key of 26 characters.
Each of these functions returns a string. A model with a string primary key doesn't generate its ID, so set the ID before you create the model:
1post := models.Post{ID: str.UUID7(), Title: "My first post"}2if err := model.Create(r, &post); err != nil {3 return web.Fail(err)4}1post := models.Post{ID: str.UUID7(), Title: "My first post"}2if err := model.Create(r, &post); err != nil {3 return web.Fail(err)4}
Numbers
When you show a count, a file's size, or a rank, you'll want it formatted the way people read it, such as 1,234,567 rather than 1234567. The number package handles this, and each of its functions takes any integer or floating-point type, so you may pass a model's int64 count or a float64 average without converting it:
| Function | Result |
|---|---|
number.Format(1234567) |
1,234,567 |
number.Format(1234.567, |
1,234.57 |
number.Abbreviate(1_250_000) |
1.3M |
number.FileSize(1536) |
1.5 KB |
number.Percentage(87.25, |
87.3% |
number.Ordinal(22) |
22nd |
A half rounds away from zero, so number.Format(1234.5) is 1,235. Every function uses English formats, which put a comma between thousands and a period before decimals.
Money
Money needs exact amounts, so a total never picks up a floating-point error. Applications store it as a whole number of cents, or as a numeric.Decimal in a decimal column. number.Cents shows an amount stored in cents, and number.Currency shows one in whole units:
1number.Cents(199950, "USD") // $1,999.502number.Currency(19.5, "EUR") // €19.503number.Currency(1999.5, "CHF") // 1,999.50 CHF1number.Cents(199950, "USD") // $1,999.502number.Currency(19.5, "EUR") // €19.503number.Currency(1999.5, "CHF") // 1,999.50 CHF
USD, EUR, GBP, JPY, CAD, and AUD show their sign before the amount. Other currencies show their code after it. Currencies without a minor unit, such as the yen and the won, show no decimals, and because their amounts are stored in whole units, number.Cents doesn't divide them:
1number.Currency(1999, "JPY") // ¥1,9992number.Cents(1999, "JPY") // ¥1,9991number.Currency(1999, "JPY") // ¥1,9992number.Cents(1999, "JPY") // ¥1,999
To show a numeric.Decimal, round it to the currency's decimals first, which is exact, then pass it as a float64:
1number.Currency(invoice.Total.Round(2).Float64(), "USD") // $1,883.551number.Currency(invoice.Total.Round(2).Float64(), "USD") // $1,883.55
Round a numeric.Decimal before you convert it. A float64 can't hold every half cent exactly, so an unrounded 1.005 shows as $1.00 rather than $1.01.