# General Translation Platform: standardizeLocale URL: https://generaltranslation.com/zh/docs/platform/core/reference/utility-functions/locales/standardize-locale.mdx --- title: standardizeLocale description: 无需 GT 实例,即可将区域设置代码规范化为标准格式。standardizeLocale 的 API 参考。 --- [`standardizeLocale`](/docs/platform/core/reference/gt-class-methods/locales/standardize-locale) 是 General Translation 核心库中的一个独立工具函数,可将 BCP-47 区域设置代码规范化为其标准形式,并校正大小写。 ## 概览 [#overview] 直接从 `generaltranslation` 导入 `standardizeLocale`,并传入一个区域设置代码进行调用。它不需要 API Key,也不需要 [GT](/docs/platform/core/reference/gt-class/constructor) 实例。若要使用基于实例的等效方式,请改用 [`GT`](/docs/platform/core/reference/gt-class/constructor) 实例上的 [`standardizeLocale`](/docs/platform/core/reference/gt-class-methods/locales/standardize-locale) 方法。 ```typescript import { standardizeLocale } from 'generaltranslation'; // 规范化大小写 console.log(standardizeLocale('EN-gb')); // 'en-GB' console.log(standardizeLocale('fr-ca')); // 'fr-CA' // 已标准化的区域设置直接透传 console.log(standardizeLocale('es-ES')); // 'es-ES' ``` 签名: ```typescript standardizeLocale(locale: string): string ``` ## 工作原理 [#how-it-works] * **规范化。** 将输入传递给 `Intl.getCanonicalLocales`,并返回第一个规范化后的结果,它会统一大小写格式 (language 小写、region 大写、script 首字母大写) 。 * **回退。** 如果输入无法规范化,则会原样返回原始输入字符串。 ## 参数 [#parameters] | 参数 | 描述 | 类型 | 可选 | 默认值 | | ------------------- | ---------------------- | -------- | -- | --- | | [`locale`](#locale) | 要进行标准化的 BCP-47 区域设置代码。 | `string` | 否 | — | ### `locale` [#locale] **类型** `string` · **必填** 待标准化的 BCP-47 区域设置代码。 ## 返回值 [#returns] **类型** `string` 标准化后的 BCP-47 区域设置代码;如果无法标准化,则返回原始输入字符串。 ## 示例 [#examples] ```typescript import { standardizeLocale } from 'generaltranslation'; // 规范化带连字符标签的大小写 console.log(standardizeLocale('EN-gb')); // 'en-GB' console.log(standardizeLocale('fr-ca')); // 'fr-CA' console.log(standardizeLocale('en-us')); // 'en-US' // 已标准化的区域设置直接通过 console.log(standardizeLocale('es-ES')); // 'es-ES' // 无法规范化的输入将原样返回 console.log(standardizeLocale('en_us')); // 'en_us'(下划线不是有效的 BCP-47 格式) console.log(standardizeLocale('not a locale')); // 'not a locale' ``` ```typescript import { standardizeLocale, isValidLocale } from 'generaltranslation'; // 规范化用户输入 function processUserInput(input: string) { const standardized = standardizeLocale(input.trim()); const isValid = isValidLocale(standardized); return { original: input, standardized, isValid, }; } // 测试各种输入 const inputs = ['EN-gb', 'FR-ca', 'invalid', 'zh-CN']; inputs.forEach((input) => { console.log(processUserInput(input)); }); ``` ## 注意事项 [#notes] * 通过 `Intl.getCanonicalLocales` 规范化大小写 (语言代码小写,区域代码大写) 。 * 对于无法规范化的输入,返回原始输入字符串。 * 对于规范化来自不同来源的区域设置输入至关重要。 * 除 `Intl` API 外,不依赖任何外部库。