7

[JavaScript] Parse Accept-Language in HTTP Request Header

 2 years ago
source link: http://siongui.github.io/2016/01/22/javascript-parse-accept-language/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

[JavaScript] Parse Accept-Language in HTTP Request Header

January 22, 2016

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;
}

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK