I can't understand this code. If this is a RegExp, can it be done in a simpler way? Or is this already widely patible? (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)&&!/(pati)/.test(u)) || (/opera/i.test(u))){
}
Is this just:
String.indexOf("webkit")
I can't understand this code. If this is a RegExp, can it be done in a simpler way? Or is this already widely patible? (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)&&!/(pati)/.test(u)) || (/opera/i.test(u))){
}
Is this just:
String.indexOf("webkit")
/…/i
is the regex case-insensitive modifier.
– Gumbo
Commented
May 16, 2009 at 9:17
"webkit".indexOf("webkit") == /webkit/i.test("webkit")
is false in fact indexOf gives 0.... thus maybe, if we just forget about performances, it could be pared to yourString.indexOf("webkit")>=0
– fedeghe
Commented
May 1, 2016 at 14:43
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 "pati") 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.
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.
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)
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
/
).
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.