首页 > 解决方案 > 从 JavaScript 中的用户代理信息获取设备名称

问题描述

我知道关于这个话题有很多问题,但没有一个对我有帮助。我知道,我无法通过 iPhone 等 JavaScript 获取设备。

所以当我运行这个命令时:

navigator.userAgent

我得到这个结果:

"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.169 Safari/537.36"

现在我想提取Macintosh左括号后的第一个单词并将其存储在一个变量中。例如,我如何使用 RegEx 来做到这一点?

标签: javascriptjqueryregex

解决方案


RegExp is all about defining the logic of your pattern. This means you need to be sure about the string format for it to work.

So for example, in the example you posted, perhaps we define the bit you want to match as:

  • "the first word after the first opening bracket"

In which case:

navigator.userAgent.match(/^[^\(]+\((\w+)/);

推荐阅读