Skip to content

Instantly share code, notes, and snippets.

@bartwttewaall
Created March 3, 2021 08:52
Show Gist options
  • Save bartwttewaall/702f4c164df2cfa2fa7791ef487a0b6c to your computer and use it in GitHub Desktop.
Save bartwttewaall/702f4c164df2cfa2fa7791ef487a0b6c to your computer and use it in GitHub Desktop.
Tests a segment in a url with a country code (en, nl) or locale pattern (en-UK, nl-BE)
function resolveLocale(url, segmentIndex, defaultLanguage = 'en') {
const segments = url.split('/');
// look for either ISO 3166-1 alpha-2 or combined with ISO 3166-2
const pattern = /\b\w{2}(-\w{2})?\b/gim;
return (segmentIndex < segments.length && pattern.test(segments[segmentIndex]))
? segments[segmentIndex]
: defaultLanguage;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment