From c32f1f683a841373712f032297cf2de726a2c8fc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Alcib=C3=ADades=20Cabral=20D=C3=ADaz?= <62911544+alcibiadesc@users.noreply.github.com> Date: Thu, 21 Mar 2024 22:35:44 +0000 Subject: [PATCH] Fixed language detection for no regional variant #175 This commit refines the approach to extracting language codes from the `Accept-Language` header. By employing a unified regex pattern, the code now efficiently captures both simple language codes and those with regional variants. The language code extraction logic now also splits on both hyphens and underscores, defaulting to the primary language code in cases of regional variants, and always converts the result to lowercase for consistent processing. --- .../multi-page/src/routes/+layout.server.js | 20 +++++++++++++++---- 1 file changed, 16 insertions(+), 4 deletions(-) diff --git a/examples/multi-page/src/routes/+layout.server.js b/examples/multi-page/src/routes/+layout.server.js index d7463e9..4f602a9 100644 --- a/examples/multi-page/src/routes/+layout.server.js +++ b/examples/multi-page/src/routes/+layout.server.js @@ -8,9 +8,21 @@ export const load = async ({ url, cookies, request }) => { let locale = (cookies.get('lang') || '').toLowerCase(); // Get user preferred locale - if (!locale) { - locale = `${`${request.headers.get('accept-language')}`.match(/[a-zA-Z]+?(?=-|_|,|;)/)}`.toLowerCase(); - } + if (!locale) { + // If no cookie is set, try to determine the locale from the 'Accept-Language' header + const acceptLanguageHeader = request.headers.get('accept-language') || ''; + // Attempt to match the language code with optional region code + let match = acceptLanguageHeader.match(/^[a-z]+(?=[-_])/i); + + // If no match is found, try to match just the language code + if (!match) { + match = acceptLanguageHeader.match(/^[a-z]+/i); + } + + // If a match is found, use it as the locale, otherwise fall back to the default locale + locale = match ? match[0].toLowerCase() : defaultLocale; + } + // Get defined locales const supportedLocales = locales.get().map((l) => l.toLowerCase()); @@ -26,4 +38,4 @@ export const load = async ({ url, cookies, request }) => { i18n: { locale, route: pathname }, translations: translations.get(), // `translations` on server contain all translations loaded by different clients }; -}; \ No newline at end of file +};