# Strings and Numbers

- [Introduction](#introduction)
- [Available functions](#available-functions)
    - [Case](#case)
    - [Plurals](#plurals)
    - [Substrings](#substrings)
    - [Replacing](#replacing)
    - [Shortening and wrapping](#shortening-and-wrapping)
    - [Padding, masking, and cleaning](#padding-masking-and-cleaning)
    - [Matching](#matching)
- [Random strings and identifiers](#random-strings-and-identifiers)
- [Numbers](#numbers)
    - [Money](#money)

<a name="introduction"></a>

## Introduction


Laravel의 `str` 패키지는 URL 슬러그 생성, 필드 라벨 형식 지정, 미리보기 자르기 같은 일반적인 작업용 문자열 헬퍼를 제공합니다. 함께 사용하는 `number` 패키지는 개수, 파일 크기, 금액을 읽기 좋게 표시합니다. 모두 일반 함수이므로 핸들러, 메일, 명령어 등 애플리케이션 어디서든 호출할 수 있습니다.

```go
import (
	"go.laravel.com/number"
	"go.laravel.com/str"
)

slug := str.Slug("My First Post")                                      // my-first-post
label := str.Headline("first_name")                                    // First Name
table := str.Plural(str.Snake("BlogPost"))                             // blog_posts
preview := str.Limit("Thanks for the detailed write-up on queues", 20) // Thanks for the detai...
views := number.Abbreviate(1_250_000)                                  // 1.3M
```


길이, 위치, 너비는 모두 바이트 대신 Unicode 문자로 세므로 `str.Take("这是一段中文", 2)`는 `"这是"`를 반환합니다.


모든 뷰는 이미 `title`, `round` 같은 일부 서식 함수를 호출할 수 있습니다. 뷰에서 `str.Limit`나 `number.Cents` 등 이 페이지의 다른 함수를 사용하려면 템플릿 가이드의 [functions of your own](/go/docs/templates#functions-of-your-own)을 참고하세요.

<a name="available-functions"></a>

## Available functions


아래 표는 `str` 패키지 함수를 분류별로 나열합니다.

<a name="case"></a>

### Case


다음 함수로 식별자와 제목의 명명 규칙을 변환할 수 있습니다.

| 함수 | 결과 |
| --- | --- |
| `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` |


연속된 대문자는 한 단어로 유지되므로 Go 필드 `UserID`는 `user_id`가 됩니다. 슬러그는 악센트 문자를 유지하므로 `str.Slug("Café")`는 `café`입니다. 악센트도 제거하려면 `str.Slug(str.ASCII("Café"))`처럼 `str.ASCII`를 먼저 호출하세요.


대소문자 변환에는 표준 라이브러리의 `strings.ToUpper`와 `strings.ToLower`를 사용하세요.

<a name="plurals"></a>

### Plurals

| 함수 | 결과 |
| --- | --- |
| `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`과 `str.Singular`는 영어 규칙을 사용합니다. `BlogPost` 같은 이름에서는 대소문자를 유지하며 마지막 단어를 바꿉니다.


게시물 댓글처럼 개수를 표시할 때 `str.Plural`에 개수를 전달할 수 있습니다. 1이면 단어를 그대로, 다른 수면 복수형으로 반환하므로 단수형용 `if`가 필요 없습니다.

```go
// 1 comment, or 3 comments
summary := fmt.Sprintf("%d %s", len(comments), str.Plural("comment", len(comments)))
```

<a name="substrings"></a>

### Substrings


다음 함수는 검색 문자열이나 문자 수를 기준으로 문자열을 자릅니다.

| 함수 | 결과 |
| --- | --- |
| `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!", 5)` | `Build` |


검색 문자열이 없으면 문자열 전체를 반환합니다. 결제 메모에서 청구서 번호를 읽을 때처럼 검색 대상의 존재 여부도 필요하면, 발견 여부도 알려주는 표준 라이브러리의 `strings.Cut`을 사용하세요.


URL의 `https://`처럼 접두사나 접미사를 한 번 제거하려면 `strings.TrimPrefix`와 `strings.TrimSuffix`를 사용하세요.

<a name="replacing"></a>

### Replacing

| 함수 | 결과 |
| --- | --- |
| `str.Start("this/string", "/")` | `/this/string` |
| `str.Finish("this/string", "/")` | `this/string/` |
| `str.ReplaceLast("the fox the dog", "the", "a")` | `the fox a dog` |
| `str.ReplaceStart("Hello World", "Hello", "Laravel")` | `Laravel World` |
| `str.ReplaceEnd("Hello World", "World", "Laravel")` | `Hello Laravel` |
| `str.Swap("Tacos are great!", map[string]string{"Tacos": "Burritos", "great": "fantastic"})` | `Burritos are fantastic!` |


`str.Start`와 `str.Finish`는 문자열 시작이나 끝에 접두사 또는 접미사가 정확히 한 번 있도록 하므로 `str.Start("//this/string", "/")`도 `/this/string`입니다. `str.ReplaceStart`와 `str.ReplaceEnd`는 검색 문자열로 시작하거나 끝날 때만 바꿉니다. `str.Swap`은 맵의 모든 키를 한 번의 처리로 바꾸므로 치환 결과를 다시 치환하지 않습니다.


모든 일치 항목을 바꾸려면 표준 라이브러리의 `strings.ReplaceAll`, 첫 항목만 바꾸려면 `strings.Replace(s, search, replace, 1)`을 사용하세요.

<a name="shortening-and-wrapping"></a>

### Shortening and wrapping


긴 게시물이나 댓글을 목록에 표시할 때는 적당한 길이의 미리보기가 필요합니다. `str.Limit`는 문자 수로, `str.Words`는 단어 수로 자릅니다.

| 함수 | 결과 |
| --- | --- |
| `str.Limit("The quick brown fox", 9)` | `The quick...` |
| `str.LimitWith("The quick brown fox", 9, " →")` | `The quick →` |
| `str.Words("Perfectly balanced, as all things should be.", 3)` | `Perfectly balanced, as...` |
| `str.WordsWith("Perfectly balanced, as all things should be.", 3, " >>>")` | `Perfectly balanced, as >>>` |
| `str.Excerpt("This is my name", "my", 3)` | `"...is my na..."`, `true` |
| `str.WordWrap("The quick brown fox", 10)` | `The quick\nbrown fox` |
| `str.WordCount("Hello   world")` | `2` |


`str.Limit`와 `str.Words`는 실제로 잘랐을 때만 끝 문자열을 추가하며 끝 문자열은 제한 길이에 포함되지 않습니다. `str.Excerpt`는 대소문자를 무시하고 처음 일치한 구절과 양쪽의 지정한 최대 문자 수를 반환합니다. 구절이 없으면 `false`를 알려주므로 검색 결과 페이지에서 일반 미리보기를 대신 쓸 수 있습니다.

```go
excerpt, ok := str.Excerpt(post.Body, query, 40)
if !ok {
	excerpt = str.Limit(post.Body, 80)
}
```

<a name="padding-masking-and-cleaning"></a>

### Padding, masking, and cleaning

| 함수 | 결과 |
| --- | --- |
| `str.PadStart("42", 5, '0')` | `00042` |
| `str.PadEnd("James", 10, '-')` | `James-----` |
| `str.PadBoth("James", 10, '_')` | `__James___` |
| `str.Mask("taylor@example.com", '*', 3)` | `tay***************` |
| `str.Mask("4242424242424242", '*', 0, -4)` | `************4242` |
| `str.Squish("  laravel    framework  ")` | `laravel framework` |
| `str.Deduplicate("/docs//strings///methods", '/')` | `/docs/strings/methods` |
| `str.Digits("(555) 123-4567")` | `5551234567` |


`str.Mask`는 문자 위치부터 끝까지 가립니다. 길이를 추가로 지정할 수 있고 음수 길이는 끝의 그만큼을 남깁니다. 카드 번호 끝 네 자리만 보이려면 `0`부터 길이 `-4`로 가리세요. 음수 위치는 끝에서 거꾸로 셉니다. 이미 지정 너비 이상인 문자열에는 패딩 함수가 원본을 반환합니다.

<a name="matching"></a>

### Matching


`str.Resembles`는 `*`가 빈 문자열을 포함한 모든 문자와 일치하는 패턴으로 문자열을 검사합니다. 대소문자를 구별하며 전체 문자열이 일치해야 하므로 경로를 패턴 목록과 비교할 때 유용합니다.

```go
str.Resembles("posts/1/edit", "posts/*") // true
str.Resembles("posts/1/edit", "*/edit")  // true
str.Resembles("posts", "posts/*")        // false
```


단순 부분 문자열, 접두사, 접미사에는 표준 라이브러리의 `strings.Contains`, `strings.HasPrefix`, `strings.HasSuffix`를 사용하세요. 더 복잡한 패턴에는 표준 [`regexp`](https://pkg.go.dev/regexp) 패키지를 사용하세요.

<a name="random-strings-and-identifiers"></a>

## Random strings and identifiers


초대 링크, API 토큰, 고유 식별자는 `str` 패키지 함수로 생성하세요. 운영체제의 암호학적으로 안전한 난수 생성기인 `crypto/rand`를 사용합니다.

```go
token := str.Random(40)      // 40 letters and digits
password := str.Password(16) // letters, digits, and symbols
id := str.UUID()             // a version 4 UUID
ordered := str.UUID7()       // a version 7 UUID, which sorts by time
ulid := str.ULID()           // a ULID, such as 01ARZ3NDEKTSV4RRFFQ69G5FAV
```


`str.UUID7`과 `str.ULID`는 앞부분에 생성 타임스탬프를 포함하므로 시간순 정렬과 데이터베이스 인덱스 추가에 적합해 무작위 `str.UUID`보다 기본 키에 유리합니다. `uuid` 컬럼에는 `str.UUID7`, 짧은 26자 키에는 `str.ULID`를 선택하세요.


각 함수는 `string`을 반환합니다. 문자열 [primary key](/go/docs/models#primary-keys)를 가진 모델은 ID를 생성하지 않으므로 모델 생성 전에 ID를 지정하세요.

```go
post := models.Post{ID: str.UUID7(), Title: "My first post"}
if err := model.Create(r, &post); err != nil {
	return web.Fail(err)
}
```

<a name="numbers"></a>

## Numbers


개수, 파일 크기, 순위를 표시할 때는 `1234567`보다 `1,234,567`처럼 읽기 좋은 형식이 필요합니다. `number` 패키지는 모든 정수나 부동소수점 타입을 받으므로 모델의 `int64` 개수나 `float64` 평균을 변환 없이 전달할 수 있습니다.

| 함수 | 결과 |
| --- | --- |
| `number.Format(1234567)` | `1,234,567` |
| `number.Format(1234.567, 2)` | `1,234.57` |
| `number.Abbreviate(1_250_000)` | `1.3M` |
| `number.FileSize(1536)` | `1.5 KB` |
| `number.Percentage(87.25, 1)` | `87.3%` |
| `number.Ordinal(22)` | `22nd` |


절반인 값은 0에서 멀어지는 쪽으로 반올림하므로 `number.Format(1234.5)`는 `1,235`입니다. 모든 함수는 천 단위 쉼표와 소수점 앞 마침표를 사용하는 영어 형식입니다.

<a name="money"></a>

### Money


금액에는 합계에 부동소수점 오차가 생기지 않도록 정확한 값이 필요합니다. 애플리케이션은 정수 센트 또는 `decimal` 컬럼의 [`numeric.Decimal`](/go/docs/database#dates-times-and-decimals)로 저장합니다. `number.Cents`는 센트 단위 값을, `number.Currency`는 기본 통화 단위 값을 표시합니다.

```go
number.Cents(199950, "USD")    // $1,999.50
number.Currency(19.5, "EUR")   // €19.50
number.Currency(1999.5, "CHF") // 1,999.50 CHF
```


`USD`, `EUR`, `GBP`, `JPY`, `CAD`, `AUD`는 금액 앞에 기호를 붙이고 다른 통화는 뒤에 코드를 붙입니다. 엔이나 원처럼 보조 단위가 없는 통화는 소수를 표시하지 않습니다. 이런 금액은 기본 단위로 저장하므로 `number.Cents`도 나누지 않습니다.

```go
number.Currency(1999, "JPY") // ¥1,999
number.Cents(1999, "JPY")    // ¥1,999
```


`numeric.Decimal`을 표시하려면 먼저 해당 통화의 소수 자릿수로 정확하게 반올림한 다음 `float64`로 전달하세요.

```go
number.Currency(invoice.Total.Round(2).Float64(), "USD") // $1,883.55
```

> [!WARNING]
> `numeric.Decimal`은 변환 전에 반올림하세요. `float64`는 모든 반 센트를 정확하게 표현할 수 없으므로 반올림하지 않은 `1.005`는 `$1.01` 대신 `$1.00`으로 표시됩니다.