title: User Agent parsing in Javascript
body: <p>I need to extract the Operating System's name and the browser's name from the user agent string.</p>
  
  <p>Sample of user agent:</p>
  
  <pre><code>Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.2.9) Gecko/20100825 Ubuntu/9.10 (karmic) Firefox/3.6.9
  </code></pre>
  
  <p>How can I get just the operating system (example <code>"Linux i686"</code> and <code>"Firefox 3.6.9"</code>)?</p>
  
  <p>Here is my codes in fiddle <a href="http://jsfiddle.net/Q89b6/" rel="nofollow noreferrer">link</a> which is as follows:</p>
  
  <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
  <div class="snippet-code">
  <pre class="snippet-code-js lang-js prettyprint-override"><code>function getBrowserAndOS(userAgent, elements) {
    var browserList = {
        'Chrome': [/Chrome\/(\S+)/],
        'Firefox': [/Firefox\/(\S+)/],
        'MSIE': [/MSIE (\S+);/],
        'Opera': [
          /Opera\/.*?Version\/(\S+)/,
          /Opera\/(\S+)/
        ],
        'Safari': [/Version\/(\S+).*?Safari\//]
      },
      re, m, browser, version;
  
  
    var osList = {
        'Windows': [/Windows\/(\S+)/],
        'Linux': [/Linux\/(\S+)/]
      },
      re2, m2, os;
  
    if (userAgent === undefined)
      userAgent = navigator.userAgent;
  
    if (elements === undefined)
      elements = 2;
    else if (elements === 0)
      elements = 1337;
  
    for (browser in browserList) {
      while (re = browserList[browser].shift()) {
        if (m = userAgent.match(re)) {
          version = (m[1].match(new RegExp('[^.]+(?:\.[^.]+){0,' + --elements + '}')))[0];
          //version = (m[1].match(new RegExp('[^.]+(?:\.[^.]+){0,}')))[0];
          //return browser + ' ' + version;
          console.log(browser + ' ' + version);
        }
      }
    }
  
  
    for (os in osList) {
      while (re2 = osList[os].shift()) {
        if (m2 = userAgent.match(re2)) {
          //version = (m[1].match(new RegExp('[^.]+(?:\.[^.]+){0,' + --elements + '}')))[0];
          //version = (m[1].match(new RegExp('[^.]+(?:\.[^.]+){0,}')))[0];
          //return browser + ' ' + version;
          console.log(os);
        }
  
      }
    }
  
    return null;
  }
  
  console.log(getBrowserAndOS(navigator.userAgent, 2));</code></pre>
  </div>
  </div>
  </p>
  
  <p>I just need to extract the OS name and the browser name with their respective versions. How can I parse it to get those string?</p>