Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

improve browser language detection by using two-letter codes #12

Merged
merged 1 commit into from
Dec 9, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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