javascript - regex matching devices on user agent

非 Y 不嫁゛ 提交于 2020-01-25 08:15:40

问题


I'm using the PHP class "Mobile Detect" to detect user device type (tablet/phone) however I also want to detect certain devices in javascript. Can someone help me convert the following into javascript regex (just need a true/false return)?

var user_agent = navigator.userAgent;

var samsung = 'Galaxy.*Tab|SAMSUNG.*Tablet|Galaxy.*Tab|Android.*GT-';
// if statement checking samsung regex against user agent

var nexus = '^.*Android.*Nexus(((?:(?!Mobile))|(?:(\s(7).+))).)*$';
// if statement checking nexus7 regex against user agent

回答1:


Are you looking for something like this?

var user_agent = navigator.userAgent;

var samsung = /Galaxy.*Tab|SAMSUNG.*Tablet|Galaxy.*Tab|Android.*GT-/i;
// if statement checking samsung regex against user agent
if (samsung.test(user_agent)) {
   // This is a samsung mobile device
}

var nexus = /^.*Android.*Nexus(((?:(?!Mobile))|(?:(\s(7).+))).)*$/i;
// if statement checking nexus7 regex against user agent
if (nexus.test(user_agent)) {
   // This is a nexus mobile device
}

Or did you actually want help fixing malfunctioning / incomplete regular expressions?

If you need a solid regular expression, I suggest you go play around at txt2re.com it's the best regular expression generator I know of.



来源:https://stackoverflow.com/questions/14507996/javascript-regex-matching-devices-on-user-agent

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!