# General Translation Platform: standardizeLocale
URL: https://generaltranslation.com/zh/docs/platform/core/reference/gt-class-methods/locales/standardize-locale.mdx
Docs index: https://generaltranslation.com/llms.txt
Description: 将区域设置代码规范为标准格式。standardizeLocale 的 API 参考。

将 BCP-47 区域设置代码标准化，确保 [GT](/docs/platform/core/reference/gt-class/constructor) 实例中的格式和大小写正确无误。General Translation 会将区域设置代码转换为其规范形式，使其在整个应用中保持一致，并可用于国际化 API。

## 概览 [#overview]

在 [`GT`](/docs/platform/core/reference/gt-class/constructor) 实例上调用 `standardizeLocale` 时，可选择传入区域设置代码。若省略，则使用该实例的 `targetLocale`。

```typescript
const gt = new GT({ sourceLocale: 'en', targetLocale: 'es-ES' });

console.log(gt.standardizeLocale('en-us')); // "en-US"
```

签名：

```typescript
standardizeLocale(locale?: string): string
```

*注意：`standardizeLocale` 在本地运行，无需 API 密钥。省略 `locale` 时，它会使用实例的 `targetLocale`。如果想在不使用 `GT` 实例的情况下进行标准化，请参阅独立版 [`standardizeLocale`](/docs/platform/core/reference/utility-functions/locales/standardize-locale)。*

## 工作方式 [#how-it-works]

* **规范化。** 交由 `Intl.getCanonicalLocales` 处理，它会规范大小写：语言子标签转为小写，区域子标签转为大写。
* **区域设置后备。** 省略 `locale` 时，会使用实例的 `targetLocale`。
* **失败时原样返回。** 如果无法标准化，则会原样返回输入字符串。
* **缺少区域设置。** 如果未提供 `locale`，且实例也未配置 `targetLocale`，则会抛出 `Error`。

连字符代码常见的大小写修正如下：

* `en-us` → `en-US` (区域转为大写) 
* `EN-gb` → `en-GB` (语言转为小写，区域转为大写) 
* `fr-ca` → `fr-CA` (整体大小写均已规范)

## 参数 [#parameters]

| 参数                  | 描述                   | 类型       | 可选 | 默认值                 |
| ------------------- | -------------------- | -------- | -- | ------------------- |
| [`locale`](#locale) | 要规范化的 BCP-47 区域设置代码。 | `string` | 是  | `this.targetLocale` |

### `locale` [#locale]

**类型** `string` · **可选** · **默认值** `this.targetLocale`

要进行标准化的 BCP-47 区域设置代码。若未提供，则使用该实例的 `targetLocale`。

## 返回值 [#returns]

**类型** `string`

标准化的 BCP-47 区域设置代码；如果无法标准化，则原样返回输入字符串。如果未提供 `locale`，且该实例未配置 `targetLocale`，则会抛出 `Error`。

## 示例 [#examples]

```typescript
const gt = new GT({ sourceLocale: 'en', targetLocale: 'es-ES' });

// 连字符代码的大小写将被标准化
console.log(gt.standardizeLocale('en-us')); // "en-US"
console.log(gt.standardizeLocale('EN-gb')); // "en-GB"
console.log(gt.standardizeLocale('fr-ca')); // "fr-CA"

// 已标准化的区域设置将原样通过，不做更改
console.log(gt.standardizeLocale('es-ES')); // "es-ES"
console.log(gt.standardizeLocale('ja-JP')); // "ja-JP"
```

## 说明 [#notes]

* 统一规范大小写：语言代码转为小写，区域代码转为大写。
* 如果代码无法标准化，则原样返回输入 string。
* 如存在区域设置扩展和变体，则予以保留。

## Sitemap

See the full [sitemap](https://generaltranslation.com/sitemap.md) for all pages.
