Skip to content

Instantly share code, notes, and snippets.

@z-------------
Created June 17, 2020 10:28
Show Gist options
  • Save z-------------/9aa1e57fe50b22b7a4cbe1c9042dbe22 to your computer and use it in GitHub Desktop.
Save z-------------/9aa1e57fe50b22b7a4cbe1c9042dbe22 to your computer and use it in GitHub Desktop.
interface UserAgentInfoPart {
name: string;
version?: string;
detail?: string[];
}
type UserAgentInfo = UserAgentInfoPart[];
const re = /(\w+)(\/([0-9.]+))?( \((.*)\))?/g;
/**
* Parse a user agent string into logical parts.
*
* @param userAgentStr - The user agent string to parse
* @return The information parsed from the user agent string
*/
export default function parseUserAgent(userAgentStr: string): UserAgentInfo {
const parsed = [];
let match = re.exec(userAgentStr);
while (match) {
parsed.push({
name: match[1],
version: match[3],
detail: match[5]?.split(";").map(str => str.trim()),
});
match = re.exec(userAgentStr);
}
return parsed;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment