Skip to content

Instantly share code, notes, and snippets.

@odyniec
Created January 21, 2013 23:29
Show Gist options
  • Save odyniec/4590546 to your computer and use it in GitHub Desktop.
Save odyniec/4590546 to your computer and use it in GitHub Desktop.
A JavaScript function that extracts the browser name and version number from user agent string. Recognized browsers: Firefox, Internet Explorer, Opera, Chrome, and Safari.
/**
* Extracts the browser name and version number from user agent string.
*
* @param userAgent
* The user agent string to parse. If not specified, the contents of
* navigator.userAgent are parsed.
* @param elements
* How many elements of the version number should be returned. A
* value of 0 means the whole version. If not specified, defaults to
* 2 (major and minor release number).
* @return A string containing the browser name and version number, or null if
* the user agent string is unknown.
*/
function identifyBrowser(userAgent, elements) {
var regexps = {
'Chrome': [ /Chrome\/(\S+)/ ],
'Firefox': [ /Firefox\/(\S+)/ ],
'MSIE': [ /MSIE (\S+);/ ],
'Opera': [
/Opera\/.*?Version\/(\S+)/, /* Opera 10 */
/Opera\/(\S+)/ /* Opera 9 and older */
],
'Safari': [ /Version\/(\S+).*?Safari\// ]
},
re, m, browser, version;
if (userAgent === undefined)
userAgent = navigator.userAgent;
if (elements === undefined)
elements = 2;
else if (elements === 0)
elements = 1337;
for (browser in regexps)
while (re = regexps[browser].shift())
if (m = userAgent.match(re)) {
version = (m[1].match(new RegExp('[^.]+(?:\.[^.]+){0,' + --elements + '}')))[0];
return browser + ' ' + version;
}
return null;
}
@simulationguest
Copy link

simulationguest commented Jan 4, 2021

This might be helpful: Default parameters

@digioz
Copy link

digioz commented Feb 1, 2021

It doesn't resolve for Edge Browser.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment