How to detect browser & its version using javascript

Yesterday, one of my friend asked me how I can detect the browser & its version using javascript?

I suggested him to use $.browser. I wrote a sample code for him but when I tried to execute the code, it raised an error. $.browser is undefined. It was a bit surprise for me because I used it in several projects.
When I checked the jQuery documentation, I found that $.browser was removed in jQuery 1.9.

OK, no problem. I checked the Modernizr ( a JavaScript library that detects HTML5 and CSS3 features in the user’s browser ).

You can use the below script to identify browser & its version.
Based on the stackoverflow user Code's code snippet:
http://stackoverflow.com/a/13480430/1392485


var BrowserDetect = {
       init: function () {
       this.browser = this.searchString( this.dataBrowser ) || "Other";
       this.version = this.searchVersion( navigator.userAgent ) || this.searchVersion( navigator.appVersion ) || "Unknown";
    },
 
    searchString: function ( data ) {
            for ( var i = 0; i < data.length; i++ ) {
                var dataString = data[i].string;
                this.versionSearchString = data[i].subString;
                if ( dataString.indexOf( data[i].subString ) != -1 ) {
                    return data[i].identity;
                }
            }
        },
 
        searchVersion: function ( dataString ) {
            var index = dataString.indexOf( this.versionSearchString );
            if ( index == -1 ) return;
            return parseFloat( dataString.substring( index + this.versionSearchString.length + 1 ) );
        },
 
        dataBrowser:
            [
                { string: navigator.userAgent, subString: "Chrome", identity: "Chrome" },
                { string: navigator.userAgent, subString: "MSIE", identity: "Explorer" },
                { string: navigator.userAgent, subString: "Firefox", identity: "Firefox" },
                { string: navigator.userAgent, subString: "Safari", identity: "Safari" },
                { string: navigator.userAgent, subString: "Opera", identity: "Opera" },
            ]
        };
        BrowserDetect.init();
You can then simply check for:

BrowserDetect.browser == 'Explorer';

BrowserDetect.version <= 9;


You can also modify the script to include more browsers.

Happy coding !!