Skip to content

Commit c217c17

Browse files
authored
Merge pull request #12 from aboutbits/improve-browser-language-detection
improve browser language detection by using two-letter codes
2 parents 8cbaee6 + 2605d44 commit c217c17

File tree

1 file changed

+7
-2
lines changed

1 file changed

+7
-2
lines changed

src/index.ts

+7-2
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@ class Internationalization<T extends string> {
1616
/**
1717
* ClientInternationalization utility package for working with languages
1818
*
19-
* @param supportedLanguages { Array<string> } - List of all supported languages
19+
* @param supportedLanguages { Array<string> } - List of all supported languages as two-letter codes (ISO 639-1)
2020
* @param fallbackLanguage { string } - Fallback language if no language matches
2121
* @param cookieName { string } - Optional: Set a preferred cookie name
2222
*/
@@ -43,9 +43,14 @@ class Internationalization<T extends string> {
4343
// If the DOM isn't accessible the website may be rendered on a server
4444
if (canUseDOM()) {
4545
// Get browser language
46-
const browserLanguage =
46+
let browserLanguage =
4747
(navigator.languages && navigator.languages[0]) || navigator.language
4848

49+
// Check if the browser language is in the format of xx-XX, extract the first part
50+
if (/^[a-zA-z]{2}\-/.test(browserLanguage)) {
51+
browserLanguage = browserLanguage.substring(0, 2)
52+
}
53+
4954
return (
5055
this.supportedLanguages.find((lang) =>
5156
isEqualCaseInsensitive(lang, browserLanguage),

0 commit comments

Comments
 (0)