Last active
December 19, 2015 19:38
-
-
Save myadzel/6007043 to your computer and use it in GitHub Desktop.
Detection and parsing "accept language" and browser language
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(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