Skip to content

Instantly share code, notes, and snippets.

@jpomykala
Last active April 13, 2021 11:04
Show Gist options
  • Save jpomykala/adf62185cfad22efceb151fde909af35 to your computer and use it in GitHub Desktop.
Save jpomykala/adf62185cfad22efceb151fde909af35 to your computer and use it in GitHub Desktop.
Detecting browser locale for SimpleLocalize.io
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