Skip to content

Instantly share code, notes, and snippets.

@myadzel
Last active December 19, 2015 19:38
Show Gist options
  • Save myadzel/6007043 to your computer and use it in GitHub Desktop.
Save myadzel/6007043 to your computer and use it in GitHub Desktop.
Detection and parsing "accept language" and browser language
(function ($) {
$.ajax({
url: "http://ajaxhttpheaders.appspot.com",
dataType: "jsonp",
success: function (headers) {
language = headers["Accept-Language"];
console.log({
"browser": getBrowserLanguage(),
"accept": getAcceptLanguageCodes(language)
});
}
});
function getAcceptLanguageCodes(s) {
var accept = [],
pairs = ("" + s).split(/,\s*/);
for (var i = 0, acceptNames = {}, code; i < pairs.length; i++) {
if (code = pairs[i].match(/^([a-z]{2})(-[a-z]{2})?(;|$)/i)) {
code = code[1];
if (typeof acceptNames[code] == "undefined") {
accept.push(code);
acceptNames[code] = true;
}
}
}
return accept;
}
function getBrowserLanguage() {
return getAcceptLanguageCodes(window.navigator.userLanguage || window.navigator.language)[0];
}
})(jQuery);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment