[JavaScript] Parse Accept-Language in HTTP Request Header


This post is the JavaScript version of my previous posts [1] and [3]. This JavaScript example parses Accept-Language string in HTTP Request Header and output (languageTag, quality) pairs:

/**
 * Parse HTTP accept-language header of the user browser.
 *
 * @param {string} hdr The string of accpet-language header
 * @return {Array} Array of language-quality pairs
 */
function getParsedAcceptLangs(hdr) {
  var pairs = hdr.split(',');
  var result = [];
  for (var i=0; i < pairs.length; i++) {
    var pair = pairs[i].split(';');
    if (pair.length == 1) result.push( [pair[0], '1'] );
    else result.push( [pair[0], pair[1].split('=')[1] ] );
  }
  return result;
}

You can use this information to determine user locale.


References:

[1][Python] Parse Accept-Language in HTTP Request Header
[2]Detect User Language (Locale) on Google App Engine Python
[3][Golang] Parse Accept-Language in HTTP Request Header
[4]List of HTTP header fields
[5]HTTP/1.1: Header Field Definitions
[6]Accept-Language used for locale setting
[7]localization - JavaScript for detecting browser language preference - Stack Overflow
[8]NavigatorLanguage.languages - Web APIs | MDN
[9]Accessing the web page's HTTP Headers in JavaScript - Stack Overflow
[10]How do I access the HTTP request header fields via JavaScript? - Stack Overflow
[11]XML DOM - HttpRequest object