Last active
April 13, 2021 11:04
-
-
Save jpomykala/adf62185cfad22efceb151fde909af35 to your computer and use it in GitHub Desktop.
Detecting browser locale for SimpleLocalize.io
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
export const LOCALE_PATTERN = /[a-z]{2}_[A-Z]{2}/gi; | |
export const isLocaleValid = (locale: string): boolean => { | |
return Boolean(new RegExp(LOCALE_PATTERN).test(locale)); | |
} | |
export const getBrowserLocaleOrNull = (): string | null => { | |
const locale = window.navigator.language; //won't work on SSR | |
if (!locale) { | |
return null; | |
} | |
if (locale.length === 2) { | |
if(locale === "en") { | |
return "en_US"; | |
} | |
return `${locale}_${locale.toUpperCase()}`; | |
} | |
if (locale.length === 4 && locale.includes("-")) { | |
return locale.replace(/-/g, "_"); | |
} | |
return null; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment