So, we can write the following code:
Copy the code as follows:<script type="text/javascript">
var Sys = {};
var ua = navigator.userAgent.toLowerCase();
var s;
(s = ua.match(/msie ([/d.]+)/)) ? Sys.ie = s[1] :
(s = ua.match(/firefox//([/d.]+)/)) ? Sys.firefox = s[1] :
(s = ua.match(/chrome//([/d.]+)/)) ? Sys.chrome = s[1] :
(s = ua.match(/opera.([/d.]+)/)) ? Sys.opera = s[1] :
(s = ua.match(/version//([/d.]+).*safari/)) ? Sys.safari = s[1] : 0;
//The following tests
if (Sys.ie) document.write('IE: ' + Sys.ie);
if (Sys.firefox) document.write('Firefox: ' + Sys.firefox);
if (Sys.chrome) document.write('Chrome: ' + Sys.chrome);
if (Sys.opera) document.write('Opera: ' + Sys.opera);
if (Sys.safari) document.write('Safari: ' + Sys.safari);
</script>
Among them, judgment expressions such as ternary operators are used to simplify the code. The judgment condition is an assignment statement that not only completes the matching of regular expressions and the copying of the result, but also directly uses the conditional judgment. The subsequent version information only needs to be extracted from the previous matching results, which is very efficient code.
In the future, you only need to judge a certain browser in the form of if (Sys.ie) or if (Sys.firefox), and you only need to judge the browser version in the form of if (Sys.ie == '8.0') or if (Sys.firefox == '3.0'), which is still very elegant to express.
Obtain the operating system version:
Copy the code as follows:<script type="text/javascript">
// Used to get the system version (Note: This method is invalid for Firefox and Chrome)
var ua = window.navigator.userAgent;
var osVersion = ua.split(";")[2];
var osV = osVersion.substr(osVersion.length-3,3);
switch(osV)
{
case "5.0":
document.write("Windows2000");
break;
case "5.1":
document.write("WindowsXP");
break;
case "5.2":
document.write("Windows2003");
break;
case "6":
document.write("Windows Vista");
break;
case "6.1":
document.write("Windows 7");
break;
default:
document.write("Others");
}
</script>