DEV Community

Discussion on: Vanilla JavaScript detecting the operating system

Collapse
 
lexlohr profile image
Alex Lohr

This seems like a prime example for the use of regexp:

/\b(?:Win|Mac|X11|Linux)/.test(navigator.appVersion) 
  ? ({ Win: "Windows", Mac: "MacOS", X11: "UNIX", Linux: "Linux" })[RegExp.$1]
  : 'unknown'
Enter fullscreen mode Exit fullscreen mode
Collapse
 
dailydevtips1 profile image
Chris Bongers

Always improving! Nice one

Collapse
 
saschalalala profile image
Sascha

How would I use this? For me, it returns undefined in both, Firefox and Chrome. The test itself returns true (as expected).

Collapse
 
amarok24 profile image
Jan Prazak

I would use match instead of test, because I also don't know how "test" should properly work in this case.

const OS = navigator.appVersion.match(/\b(?:Win|Mac|X11|Linux)/)[0];
console.log(OS);
Enter fullscreen mode Exit fullscreen mode
Thread Thread
 
dailydevtips1 profile image
Chris Bongers

Yeah match will work perfectly for this.