From 2605d449110fcd231768eed333e020ab8b334723 Mon Sep 17 00:00:00 2001 From: Lukas Weiss Date: Mon, 9 Dec 2024 12:18:59 +0100 Subject: [PATCH] improve browser language detection by using two-letter codes --- src/index.ts | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/src/index.ts b/src/index.ts index fde0d51..e589428 100644 --- a/src/index.ts +++ b/src/index.ts @@ -16,7 +16,7 @@ class Internationalization { /** * ClientInternationalization utility package for working with languages * - * @param supportedLanguages { Array } - List of all supported languages + * @param supportedLanguages { Array } - List of all supported languages as two-letter codes (ISO 639-1) * @param fallbackLanguage { string } - Fallback language if no language matches * @param cookieName { string } - Optional: Set a preferred cookie name */ @@ -43,9 +43,14 @@ class Internationalization { // If the DOM isn't accessible the website may be rendered on a server if (canUseDOM()) { // Get browser language - const browserLanguage = + let browserLanguage = (navigator.languages && navigator.languages[0]) || navigator.language + // Check if the browser language is in the format of xx-XX, extract the first part + if (/^[a-zA-z]{2}\-/.test(browserLanguage)) { + browserLanguage = browserLanguage.substring(0, 2) + } + return ( this.supportedLanguages.find((lang) => isEqualCaseInsensitive(lang, browserLanguage),