Skip to content

Instantly share code, notes, and snippets.

@abdelfattahradwan
Created May 10, 2024 20:34
Show Gist options
  • Save abdelfattahradwan/8c0d7082815068a0964a2b18a2cb8d1e to your computer and use it in GitHub Desktop.
Save abdelfattahradwan/8c0d7082815068a0964a2b18a2cb8d1e to your computer and use it in GitHub Desktop.
const ACCEPT_LANGUAGE_REGEX =
/(?<code>[a-zA-Z]{1,8})(?:-(?<region>[a-zA-Z]{1,8}))?(?:;q=(?<quality>0\.\d+|\d))?/g;
type Language = {
code: string;
region?: string;
quality: number;
};
export default function parseAcceptLanguage(header: string): Array<Language> {
const result = new Array<Language>();
let match: RegExpExecArray | null;
while ((match = ACCEPT_LANGUAGE_REGEX.exec(header)) !== null) {
if (match.groups) {
const code = match.groups["code"];
const region = match.groups["region"];
const quality = match.groups["quality"]
? parseFloat(match.groups["quality"])
: 1.0;
result.push({ code, region, quality });
}
}
return result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment