tags:

views:

191

answers:

5

I can't understand this code. If this is a RegExp, can it be done in a simpler way? Or is this already widely compatible? (with IE6 and newer browsers)

var u = navigator.userAgent;

// Webkit - Safari
   if(/webkit/i.test(u)){
// Gecko - Firefox, Opera
   }else if((/mozilla/i.test(u)&&!/(compati)/.test(u)) || (/opera/i.test(u))){
   }

Is this just:

String.indexOf("webkit")
+3  A: 

test() in javascript is a regular expression test function. You can read more about it here.

This method tests for a match of a regular expression in a string, returning true if successful, and false if not. The test method can be used with either a string literal or a string variable.

Code:

rexp = /er/
if(rexp.test("the fisherman"))
   document.write("It's true, I tell you.")

Output:

It's true, I tell you.

Also here's another great page that goes into more detail on this function.

Executes the search for a match between a regular expression and a specified string. Returns true or false.

Ólafur Waage
A: 

Method test of the regular expressions tests for a match of a regular expression in a string, returning true if successful, and false if not.

this code tests for a match of the regular expressions 'webkit', 'mozilla' etc in the string in u variable.

dasha salo
+1  A: 

You code seems to be some kind of browser sniffing. The value of u is probalby the user agent identifier. And it’s tested with regular expressions (build using the RegExp literal syntax /expr/).

Gumbo
+6  A: 

First it looks for "webkit" (ignoring case) in the string u in an attempt to determine that the browser is Safari.

If it doesn't find that, it looks for "mozilla" (without "compati") or "opera" in an attempt to determine that the browser is Firefox or Opera. Again, the searches are ignoring case (/i).

EDIT

The /.../i.test() code is a regular expression, these are built into JavaScript.

Dave Cluderay
Terse and explanatory. Thanks!
Jenko
+1  A: 

This is similar, but returns a client name and version for any browser.

window.navigator.sayswho= (function(){
    var N= navigator.appName, ua= navigator.userAgent, tem;
    var M= ua.match(/(opera|chrome|safari|firefox|msie)\/? *(\.?\d+(\.\d+)*)/i);
    if(M && (tem= ua.match(/version\/([\.\d]+)/i))!= null) M[2]= tem[1];
    M= M? [M[1], M[2]]: [N, navigator.appVersion, '-?'];
    return M;
})();

alert(navigator.sayswho)

kennebec
Not guaranteed to be the correct name, just the name returned from the client's navigator object.
kennebec
Nice! Could be useful.
Jenko