javascriptandroidregexdevice-name

RegEx: Match Android device name with JavaScript


I want to match the name of an Android device (e.g. "Galaxy Nexus") with a JavaScript RegEx pattern.

My user agent looks like this:

"Mozilla/5.0 (Linux; U; Android 4.0.2; en-us; Galaxy Nexus Build/ICL53F) AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 Mobile Safari/534.30"

If I take everything between the ";" and "Build/" then I get the device name. But it has to be the last occurence of ";" before "Build/".

At the moment I have the following expression:

var match = navigator.userAgent.match(/;[\s\S]*Build/)[0];

The problem is, that my expression takes everything between the FIRST semicolon and INCLUDES "Build/". So I get:

"; U; Android 4.0.2; en-us; Galaxy Nexus Build"

Does anyone knows how I can make my expression smarter to just get "Galaxy Nexus Build"?


Solution

  • You can test :

    var txt = "Mozilla/5.0 (Linux; U; Android 4.0.2; en-us; Galaxy Nexus Build/ICL53F) AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 Mobile Safari/534.30";
    var regex = /;\s*([^;]+)\s+Build\//g;
    var match = regex.exec(txt)[1];
    alert("#" + match + "#");
    

    http://jsfiddle.net/7AMrt/