Skip to content

Commit

Permalink
improve browser language detection by using two-letter codes
Browse files Browse the repository at this point in the history
  • Loading branch information
lukasvice committed Dec 9, 2024
1 parent 8cbaee6 commit 2605d44
Showing 1 changed file with 7 additions and 2 deletions.
9 changes: 7 additions & 2 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ class Internationalization<T extends string> {
/**
* ClientInternationalization utility package for working with languages
*
* @param supportedLanguages { Array<string> } - List of all supported languages
* @param supportedLanguages { Array<string> } - 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
*/
Expand All @@ -43,9 +43,14 @@ class Internationalization<T extends string> {
// 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),
Expand Down

0 comments on commit 2605d44

Please sign in to comment.