Created
January 21, 2013 23:29
-
-
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.
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
/** | |
* 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; | |
} |
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
This might be helpful: Default parameters