【发布时间】:2021-02-04 02:18:37
【问题描述】:
在 Internet Explorer 和 Microsoft Edge 上运行时,我需要打印浏览器名称和版本。以下代码适用于 chrome,但不适用于 IE 和 Edge。那么有人可以解释下面的代码(这些字符是什么(?=/))/?\s *(\ d +)/ i),tem ..etc)。这段代码是别人写的。 比你
getBrowserVersion(){
var userAgent= navigator.userAgent, tem,
matchTest= userAgent.match(/(opera|chrome|safari|firefox|msie|trident(?=\/))\/?\s*(\d+)/i) || [];
if(/trident/i.test(matchTest[1])){
tem= /\brv[ :]+(\d+)/g.exec(userAgent) || [];
return 'IE '+(tem[1] || '');
}
if(matchTest[1]=== 'Chrome'){
tem= userAgent.match(/\b(OPR|Edge)\/(\d+)/);
if(tem!= null) return tem.slice(1).join(' ').replace('OPR', 'Opera');
}
matchTest= matchTest[2]? [matchTest[1], matchTest[2]]: [navigator.appName, navigator.appVersion, '-?'];
if((tem= userAgent.match(/version\/(\d+)/i))!= null) matchTest.splice(1, 1, tem[1]);
return matchTest.join(' ');
}
【问题讨论】:
-
这些字符正在创建regular expressions 以定义要在字符串中匹配的字符模式。
标签: javascript typescript user-agent