Created
January 7, 2022 09:05
-
-
Save wenshin/6e5674957b4a5319e7f34a813d047e73 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
export function parseUA(ua: string) { | |
const parsed = { | |
device: 'pc', | |
deviceModel: 'unknown', | |
os: 'unknown', | |
osVersion: 'unknown', | |
}; | |
const [, , info] = ua.match(/^(Mozilla|Dalvik)\/[\d.-_]+ \(([^()]+)\)/) || []; | |
const ios = info.match(/(iPad|iPhone|iPod).+?OS\s+([\d._-]+)/i); | |
if (ios) { | |
parsed.device = ios[1]; | |
parsed.deviceModel = ios[1]; | |
parsed.os = 'iOS'; | |
parsed.osVersion = ios[2]; | |
return parsed; | |
} | |
const mac = info.match(/Mac\s+OS.+?([\d._-]+)/i); | |
if (mac) { | |
parsed.os = 'macOS'; | |
parsed.osVersion = mac[1]; | |
parsed.device = 'Macintosh'; | |
parsed.deviceModel = 'Macintosh'; | |
return parsed; | |
} | |
const windows = info.match(/Windows\s+NT\s+([\d._-]+)/i); | |
if (windows) { | |
parsed.os = 'Windows'; | |
parsed.osVersion = windows[1]; | |
} | |
const elems = info ? info.split(';') : []; | |
for (let i = 0; i < elems.length; i++) { | |
const str = elems[i].trim(); | |
const device = str.match(/(.+?)\s+Build\//i); | |
if (device && device[1]) { | |
const [d] = device[1].split(' '); | |
parsed.device = d; | |
parsed.deviceModel = device[1]; | |
} | |
const android = str.match(/Android\s+([\d._-]+)/i); | |
if (android) { | |
parsed.os = 'Android'; | |
parsed.osVersion = android[1]; | |
} | |
if (parsed.os !== 'unknown' && str.match(/Linux/i)) { | |
parsed.os = 'Linux'; | |
} | |
} | |
return parsed; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment