1 import { upperCaseFirst } from "./upper-case-first"
2
3 /**
4 * Normalizes a locale string to {@link https://developer.mozilla.org/en-US/docs/Glossary/BCP_47_language_tag|BCP 47 language tag format}
5 * @param locale - The locale string to normalize
6 * @returns The normalized locale string
7 *
8 * @example
9 * input: "en-Us"
10 * output: "en-US"
11 *
12 * @example
13 * input: "eN"
14 * output: "en"
15 *
16 * @example
17 * input: "RU-cYrl-By"
18 * output: "ru-Cyrl-BY"
19 *
20 * @example
21 * input: "zh-hans"
22 * output: "zh-Hans"
23 */
24 export function normalizeLocale(locale: string) {
25 const segments = locale.split("-")
26
27 if (segments.length === 1) {
28 return segments[0].toLowerCase()
29 }
30
31 // e.g en-US, or a script subtag such as zh-Hans
32 if (segments.length === 2) {
33 const isScript = /^[a-z]{4}$/i.test(segments[1])
34
35 return `${segments[0].toLowerCase()}-${
36 isScript
37 ? upperCaseFirst(segments[1].toLowerCase())
38 : segments[1].toUpperCase()
39 }`
40 }
41
42 // e.g ru-Cyrl-BY
43 if (segments.length === 3) {
44 return `${segments[0].toLowerCase()}-${upperCaseFirst(
45 segments[1].toLowerCase()
46 )}-${segments[2].toUpperCase()}`
47 }
48
49 return locale
50 }