As many already posted in other questions (also in jQuery documentation), the old jQuery.browser.version is deprecated and works only in jquery1.3.
Do you know another simple way to detect it, that I can include in my code before:
function handleInfoDivPopupVisibility(dynamicEleId, staticEleId){
var parentContainer = $('headerSummaryContainer');
var dynamicEle = $(dynamicEleId);
var staticEle = $(staticEleId);
if(isIE() && parentContainer){
if (jQuery.browser.version != 10) { // I need to find a way to detect if it's IE10 here.
parentContainer.style.overflow = 'visible';
}
}
dynamicEle ? dynamicEle.style.display = '' : '';
if(dynamicEle && staticEle)
gui_positionBelow(dynamicEle, staticEle);
}
Before you say it's duplicated question of this or this, I'd like to reinforce that I don't want to use css hacks. Is there a way to detect it just as simple as I could do before?
if (jQuery.browser.version != 10) {...
In general it's a bad idea to check for browser version, it's considered a better practice to check for browser features. But if you're sure what you're doing:
function getIEVersion(){
var agent = navigator.userAgent;
var reg = /MSIE\s?(\d+)(?:\.(\d+))?/i;
var matches = agent.match(reg);
if (matches != null) {
return { major: matches[1], minor: matches[2] };
}
return { major: "-1", minor: "-1" };
}
var ie_version = getIEVersion();
var is_ie10 = ie_version.major == 10;
We have the following code in production, so it works and well-tested.
And yes, we did have a need to detect IE10, not just a particular feature that exists in IE10 but not in earlier versions.
Internet Explorer has the feature of Conditional Compilation (http://www.javascriptkit.com/javatutors/conditionalcompile.shtml). You can use this:
var isIE10 = false;
/*#cc_on
if (/^10/.test(#_jscript_version)) {
isIE10 = true;
}
#*/
alert(isIE10);
DEMO: http://jsfiddle.net/X3Rvz/1/
You can put this before all your JavaScript code, and from then on just reference isIE10.
The conditional compilation won't run in non-IE, so isIE10 will still be false. And #_jscript_version will only start with 10 in IE 10.
Conditional Comments aren't supported in IE 10, and the User-Agent string can be spoofed.
Since minification usually removes comments, you can use eval or Function to find out in a similar fashion:
var isIE10 = false;
if (Function('/*#cc_on return /^10/.test(#_jscript_version) #*/')()) {
isIE10 = true;
}
DEMO: http://jsfiddle.net/wauGa/2/
UPDATE:
To still avoid minification of comments but also combine detecting any version, you can use something like:
var IE = (function () {
"use strict";
var ret, isTheBrowser,
actualVersion,
jscriptMap, jscriptVersion;
isTheBrowser = false;
jscriptMap = {
"5.5": "5.5",
"5.6": "6",
"5.7": "7",
"5.8": "8",
"9": "9",
"10": "10"
};
jscriptVersion = new Function("/*#cc_on return #_jscript_version; #*/")();
if (jscriptVersion !== undefined) {
isTheBrowser = true;
actualVersion = jscriptMap[jscriptVersion];
}
ret = {
isTheBrowser: isTheBrowser,
actualVersion: actualVersion
};
return ret;
}());
And access the properties like IE.isTheBrowser and IE.actualVersion (which is translated from internal values of JScript versions).
The jQuery.browser.version still works but you have to include the jquery-migrate plugin.
http://api.jquery.com/jQuery.browser/
https://github.com/jquery/jquery-migrate/#readme
The IE10 User-Agent String says
However if your site is still using user-agent sniffing, then increasing the “MSIE” token to “10.0” is particularly noteworthy. Why? Because it adds an extra digit to the string value of the token. Most sites will handle this effortlessly, but some will process the extra digit incorrectly, causing them to identify IE10 as IE1.
To help illustrate, here’s a regular expression that only captures the first digit of the “MSIE” token’s value:
// INCORRECT: will report IE10 version in capture 1 as "1"
var matchIE = /MSIE\s(\d)/;
And here’s one that captures the full value of the “MSIE” token:
// Correct: will report IE10 version in capture 1 as "10.0"
var matchIE = /MSIE\s([\d.]+)/
Here is a one line solution to detect IE 10
var IE10 = navigator.userAgent.toString().toLowerCase().indexOf("trident/6")>-1;
and for more information on other version and browsers please refer this Link of Browser Detection
I Found myself having a issue (border radius on frameset with legend) with IE 9 through 11 (did not check IE 12)
MSIE is no long user agent in IE 11 and the appName is Mozilla, however trident is in there
I managed to extract the trident version # and detect it
if(navigator.appVersion.indexOf('Trident/')>-1){// Begin stupid IE crap
var IE=navigator.appVersion;
IE=IE.slice(IE.indexOf('Trident/')+8);
IE=IE.slice(0,IE.indexOf(';'));
IE=Number(IE);
if(IE>=5&&IE<=7) // IE 9 through IE 11
document.body.className='ie';
}
See code:
var file1 = "50.xsl";
var file2 = "30.doc";
getFileExtension(file1); //returns xsl
getFileExtension(file2); //returns doc
function getFileExtension(filename) {
/*TODO*/
}
Newer Edit: Lots of things have changed since this question was initially posted - there's a lot of really good information in wallacer's revised answer as well as VisioN's excellent breakdown
Edit: Just because this is the accepted answer; wallacer's answer is indeed much better:
return filename.split('.').pop();
My old answer:
return /[^.]+$/.exec(filename);
Should do it.
Edit: In response to PhiLho's comment, use something like:
return (/[.]/.exec(filename)) ? /[^.]+$/.exec(filename) : undefined;
return filename.split('.').pop();
Edit:
This is another non-regex solution that I think is more efficient:
return filename.substring(filename.lastIndexOf('.')+1, filename.length) || filename;
There are some corner cases that are better handled by VisioN's answer below, particularly files with no extension (.htaccess etc included).
It's very performant, and handles corner cases in an arguably better way by returning "" instead of the full string when there's no dot or no string before the dot. It's a very well crafted solution, albeit tough to read. Stick it in your helpers lib and just use it.
Old Edit:
A safer implementation if you're going to run into files with no extension, or hidden files with no extension (see VisioN's comment to Tom's answer above) would be something along these lines
var a = filename.split(".");
if( a.length === 1 || ( a[0] === "" && a.length === 2 ) ) {
return "";
}
return a.pop(); // feel free to tack .toLowerCase() here if you want
If a.length is one, it's a visible file with no extension ie. file
If a[0] === "" and a.length === 2 it's a hidden file with no extension ie. .htaccess
This should clear up issues with the slightly more complex cases. In terms of performance, I think this solution is a little slower than regex in most browsers. However, for most common purposes this code should be perfectly usable.
The following solution is fast and short enough to use in bulk operations and save extra bytes:
return fname.slice((fname.lastIndexOf(".") - 1 >>> 0) + 2);
Here is another one-line non-regexp universal solution:
return fname.slice((Math.max(0, fname.lastIndexOf(".")) || Infinity) + 1);
Both work correctly with names having no extension (e.g. myfile) or starting with . dot (e.g. .htaccess):
"" --> ""
"name" --> ""
"name.txt" --> "txt"
".htpasswd" --> ""
"name.with.many.dots.myext" --> "myext"
If you care about the speed you may run the benchmark and check that the provided solutions are the fastest, while the short one is tremendously fast:
How the short one works:
String.lastIndexOf method returns the last position of the substring (i.e. ".") in the given string (i.e. fname). If the substring is not found method returns -1.
The "unacceptable" positions of dot in the filename are -1 and 0, which respectively refer to names with no extension (e.g. "name") and to names that start with dot (e.g. ".htaccess").
Zero-fill right shift operator (>>>) if used with zero affects negative numbers transforming -1 to 4294967295 and -2 to 4294967294, which is useful for remaining the filename unchanged in the edge cases (sort of a trick here).
String.prototype.slice extracts the part of the filename from the position that was calculated as described. If the position number is more than the length of the string method returns "".
If you want more clear solution which will work in the same way (plus with extra support of full path), check the following extended version. This solution will be slower than previous one-liners but is much easier to understand.
function getExtension(path) {
var basename = path.split(/[\\/]/).pop(), // extract file name from full path ...
// (supports `\\` and `/` separators)
pos = basename.lastIndexOf("."); // get last position of `.`
if (basename === "" || pos < 1) // if file name is empty or ...
return ""; // `.` not found (-1) or comes first (0)
return basename.slice(pos + 1); // extract extension ignoring `.`
}
console.log( getExtension("/path/to/file.ext") );
// >> "ext"
All three variants should work in any web browser on the client side and can be used in the server side NodeJS code as well.
function getFileExtension(filename)
{
var ext = /^.+\.([^.]+)$/.exec(filename);
return ext == null ? "" : ext[1];
}
Tested with
"a.b" (=> "b")
"a" (=> "")
".hidden" (=> "")
"" (=> "")
null (=> "")
Also
"a.b.c.d" (=> "d")
".a.b" (=> "b")
"a..b" (=> "b")
There is a standard library function for this in the path module:
import path from 'path';
console.log(path.extname('abc.txt'));
Output:
.txt
So, if you only want the format:
path.extname('abc.txt').slice(1) // 'txt'
If there is no extension, then the function will return an empty string:
path.extname('abc') // ''
If you are using Node, then path is built-in. If you are targetting the browser, then Webpack will bundle a path implementation for you. If you are targetting the browser without Webpack, then you can include path-browserify manually.
There is no reason to do string splitting or regex.
function getExt(filename)
{
var ext = filename.split('.').pop();
if(ext == filename) return "";
return ext;
}
var extension = fileName.substring(fileName.lastIndexOf('.')+1);
If you are dealing with web urls, you can use:
function getExt(filepath){
return filepath.split("?")[0].split("#")[0].split('.').pop();
}
getExt("../js/logic.v2.min.js") // js
getExt("http://example.net/site/page.php?id=16548") // php
getExt("http://example.net/site/page.html#welcome.to.me") // html
getExt("c:\\logs\\yesterday.log"); // log
Demo: https://jsfiddle.net/squadjot/q5ard4fj/
var parts = filename.split('.');
return parts[parts.length-1];
function file_get_ext(filename)
{
return typeof filename != "undefined" ? filename.substring(filename.lastIndexOf(".")+1, filename.length).toLowerCase() : false;
}
Code
/**
* Extract file extension from URL.
* #param {String} url
* #returns {String} File extension or empty string if no extension is present.
*/
var getFileExtension = function (url) {
"use strict";
if (url === null) {
return "";
}
var index = url.lastIndexOf("/");
if (index !== -1) {
url = url.substring(index + 1); // Keep path without its segments
}
index = url.indexOf("?");
if (index !== -1) {
url = url.substring(0, index); // Remove query
}
index = url.indexOf("#");
if (index !== -1) {
url = url.substring(0, index); // Remove fragment
}
index = url.lastIndexOf(".");
return index !== -1
? url.substring(index + 1) // Only keep file extension
: ""; // No extension found
};
Test
Notice that in the absence of a query, the fragment might still be present.
"https://www.example.com:8080/segment1/segment2/page.html?foo=bar#fragment" --> "html"
"https://www.example.com:8080/segment1/segment2/page.html#fragment" --> "html"
"https://www.example.com:8080/segment1/segment2/.htaccess?foo=bar#fragment" --> "htaccess"
"https://www.example.com:8080/segment1/segment2/page?foo=bar#fragment" --> ""
"https://www.example.com:8080/segment1/segment2/?foo=bar#fragment" --> ""
"" --> ""
null --> ""
"a.b.c.d" --> "d"
".a.b" --> "b"
".a.b." --> ""
"a...b" --> "b"
"..." --> ""
JSLint
0 Warnings.
Fast and works correctly with paths
(filename.match(/[^\\\/]\.([^.\\\/]+)$/) || [null]).pop()
Some edge cases
/path/.htaccess => null
/dir.with.dot/file => null
Solutions using split are slow and solutions with lastIndexOf don't handle edge cases.
// 获取文件后缀名
function getFileExtension(file) {
var regexp = /\.([0-9a-z]+)(?:[\?#]|$)/i;
var extension = file.match(regexp);
return extension && extension[1];
}
console.log(getFileExtension("https://www.example.com:8080/path/name/foo"));
console.log(getFileExtension("https://www.example.com:8080/path/name/foo.BAR"));
console.log(getFileExtension("https://www.example.com:8080/path/name/.quz/foo.bar?key=value#fragment"));
console.log(getFileExtension("https://www.example.com:8080/path/name/.quz.bar?key=value#fragment"));
i just wanted to share this.
fileName.slice(fileName.lastIndexOf('.'))
although this has a downfall that files with no extension will return last string.
but if you do so this will fix every thing :
function getExtention(fileName){
var i = fileName.lastIndexOf('.');
if(i === -1 ) return false;
return fileName.slice(i)
}
"one-liner" to get filename and extension using reduce and array destructuring :
var str = "filename.with_dot.png";
var [filename, extension] = str.split('.').reduce((acc, val, i, arr) => (i == arr.length - 1) ? [acc[0].substring(1), val] : [[acc[0], val].join('.')], [])
console.log({filename, extension});
with better indentation :
var str = "filename.with_dot.png";
var [filename, extension] = str.split('.')
.reduce((acc, val, i, arr) => (i == arr.length - 1)
? [acc[0].substring(1), val]
: [[acc[0], val].join('.')], [])
console.log({filename, extension});
// {
// "filename": "filename.with_dot",
// "extension": "png"
// }
There's also a simple approach using ES6 destructuring:
const path = 'hello.world.txt'
const [extension, ...nameParts] = path.split('.').reverse();
console.log('extension:', extension);
function extension(fname) {
var pos = fname.lastIndexOf(".");
var strlen = fname.length;
if (pos != -1 && strlen != pos + 1) {
var ext = fname.split(".");
var len = ext.length;
var extension = ext[len - 1].toLowerCase();
} else {
extension = "No extension found";
}
return extension;
}
//usage
extension('file.jpeg')
always returns the extension lower cas so you can check it on field change
works for:
file.JpEg
file (no extension)
file. (noextension)
This simple solution
function extension(filename) {
var r = /.+\.(.+)$/.exec(filename);
return r ? r[1] : null;
}
Tests
/* tests */
test('cat.gif', 'gif');
test('main.c', 'c');
test('file.with.multiple.dots.zip', 'zip');
test('.htaccess', null);
test('noextension.', null);
test('noextension', null);
test('', null);
// test utility function
function test(input, expect) {
var result = extension(input);
if (result === expect)
console.log(result, input);
else
console.error(result, input);
}
function extension(filename) {
var r = /.+\.(.+)$/.exec(filename);
return r ? r[1] : null;
}
I'm sure someone can, and will, minify and/or optimize my code in the future. But, as of right now, I am 200% confident that my code works in every unique situation (e.g. with just the file name only, with relative, root-relative, and absolute URL's, with fragment # tags, with query ? strings, and whatever else you may decide to throw at it), flawlessly, and with pin-point precision.
For proof, visit: https://projects.jamesandersonjr.com/web/js_projects/get_file_extension_test.php
Here's the JSFiddle: https://jsfiddle.net/JamesAndersonJr/ffcdd5z3/
Not to be overconfident, or blowing my own trumpet, but I haven't seen any block of code for this task (finding the 'correct' file extension, amidst a battery of different function input arguments) that works as well as this does.
Note: By design, if a file extension doesn't exist for the given input string, it simply returns a blank string "", not an error, nor an error message.
It takes two arguments:
String: fileNameOrURL (self-explanatory)
Boolean: showUnixDotFiles (Whether or Not to show files that begin with a dot ".")
Note (2): If you like my code, be sure to add it to your js library's, and/or repo's, because I worked hard on perfecting it, and it would be a shame to go to waste. So, without further ado, here it is:
function getFileExtension(fileNameOrURL, showUnixDotFiles)
{
/* First, let's declare some preliminary variables we'll need later on. */
var fileName;
var fileExt;
/* Now we'll create a hidden anchor ('a') element (Note: No need to append this element to the document). */
var hiddenLink = document.createElement('a');
/* Just for fun, we'll add a CSS attribute of [ style.display = "none" ]. Remember: You can never be too sure! */
hiddenLink.style.display = "none";
/* Set the 'href' attribute of the hidden link we just created, to the 'fileNameOrURL' argument received by this function. */
hiddenLink.setAttribute('href', fileNameOrURL);
/* Now, let's take advantage of the browser's built-in parser, to remove elements from the original 'fileNameOrURL' argument received by this function, without actually modifying our newly created hidden 'anchor' element.*/
fileNameOrURL = fileNameOrURL.replace(hiddenLink.protocol, ""); /* First, let's strip out the protocol, if there is one. */
fileNameOrURL = fileNameOrURL.replace(hiddenLink.hostname, ""); /* Now, we'll strip out the host-name (i.e. domain-name) if there is one. */
fileNameOrURL = fileNameOrURL.replace(":" + hiddenLink.port, ""); /* Now finally, we'll strip out the port number, if there is one (Kinda overkill though ;-)). */
/* Now, we're ready to finish processing the 'fileNameOrURL' variable by removing unnecessary parts, to isolate the file name. */
/* Operations for working with [relative, root-relative, and absolute] URL's ONLY [BEGIN] */
/* Break the possible URL at the [ '?' ] and take first part, to shave of the entire query string ( everything after the '?'), if it exist. */
fileNameOrURL = fileNameOrURL.split('?')[0];
/* Sometimes URL's don't have query's, but DO have a fragment [ # ](i.e 'reference anchor'), so we should also do the same for the fragment tag [ # ]. */
fileNameOrURL = fileNameOrURL.split('#')[0];
/* Now that we have just the URL 'ALONE', Let's remove everything to the last slash in URL, to isolate the file name. */
fileNameOrURL = fileNameOrURL.substr(1 + fileNameOrURL.lastIndexOf("/"));
/* Operations for working with [relative, root-relative, and absolute] URL's ONLY [END] */
/* Now, 'fileNameOrURL' should just be 'fileName' */
fileName = fileNameOrURL;
/* Now, we check if we should show UNIX dot-files, or not. This should be either 'true' or 'false'. */
if ( showUnixDotFiles == false )
{
/* If not ('false'), we should check if the filename starts with a period (indicating it's a UNIX dot-file). */
if ( fileName.startsWith(".") )
{
/* If so, we return a blank string to the function caller. Our job here, is done! */
return "";
};
};
/* Now, let's get everything after the period in the filename (i.e. the correct 'file extension'). */
fileExt = fileName.substr(1 + fileName.lastIndexOf("."));
/* Now that we've discovered the correct file extension, let's return it to the function caller. */
return fileExt;
};
Enjoy! You're Quite Welcome!:
Try this:
function getFileExtension(filename) {
var fileinput = document.getElementById(filename);
if (!fileinput)
return "";
var filename = fileinput.value;
if (filename.length == 0)
return "";
var dot = filename.lastIndexOf(".");
if (dot == -1)
return "";
var extension = filename.substr(dot, filename.length);
return extension;
}
If you are looking for a specific extension and know its length, you can use substr:
var file1 = "50.xsl";
if (file1.substr(-4) == '.xsl') {
// do something
}
JavaScript reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/substr
I just realized that it's not enough to put a comment on p4bl0's answer, though Tom's answer clearly solves the problem:
return filename.replace(/^.*?\.([a-zA-Z0-9]+)$/, "$1");
For most applications, a simple script such as
return /[^.]+$/.exec(filename);
would work just fine (as provided by Tom). However this is not fool proof. It does not work if the following file name is provided:
image.jpg?foo=bar
It may be a bit overkill but I would suggest using a url parser such as this one to avoid failure due to unpredictable filenames.
Using that particular function, you could get the file name like this:
var trueFileName = parse_url('image.jpg?foo=bar').file;
This will output "image.jpg" without the url vars. Then you are free to grab the file extension.
function func() {
var val = document.frm.filename.value;
var arr = val.split(".");
alert(arr[arr.length - 1]);
var arr1 = val.split("\\");
alert(arr1[arr1.length - 2]);
if (arr[1] == "gif" || arr[1] == "bmp" || arr[1] == "jpeg") {
alert("this is an image file ");
} else {
alert("this is not an image file");
}
}
I'm many moons late to the party but for simplicity I use something like this
var fileName = "I.Am.FileName.docx";
var nameLen = fileName.length;
var lastDotPos = fileName.lastIndexOf(".");
var fileNameSub = false;
if(lastDotPos === -1)
{
fileNameSub = false;
}
else
{
//Remove +1 if you want the "." left too
fileNameSub = fileName.substr(lastDotPos + 1, nameLen);
}
document.getElementById("showInMe").innerHTML = fileNameSub;
<div id="showInMe"></div>
A one line solution that will also account for query params and any characters in url.
string.match(/(.*)\??/i).shift().replace(/\?.*/, '').split('.').pop()
// Example
// some.url.com/with.in/&ot.s/files/file.jpg?spec=1&.ext=jpg
// jpg
return filename.replace(/\.([a-zA-Z0-9]+)$/, "$1");
edit: Strangely (or maybe it's not) the $1 in the second argument of the replace method doesn't seem to work... Sorry.
fetchFileExtention(fileName) {
return fileName.slice((fileName.lastIndexOf(".") - 1 >>> 0) + 2);
}
Wallacer's answer is nice, but one more checking is needed.
If file has no extension, it will use filename as extension which is not good.
Try this one:
return ( filename.indexOf('.') > 0 ) ? filename.split('.').pop().toLowerCase() : 'undefined';
Don't forget that some files can have no extension, so:
var parts = filename.split('.');
return (parts.length > 1) ? parts.pop() : '';
In some existing code there is a test to see if the user is running IE, by checking if the object Browser.Engine.trident is defined and returns true.
But how can I determine if the user is running IE6 (or earlier) or IE7 (or later)?
The test is needed inside a JavaScript function so a conditional comment doesn't seem suitable.
From detecting Internet Explorer More Effectively at msdn:
function getInternetExplorerVersion()
// Returns the version of Internet Explorer or a -1
// (indicating the use of another browser).
{
var rv = -1; // Return value assumes failure.
if (navigator.appName == 'Microsoft Internet Explorer')
{
var ua = navigator.userAgent;
var re = new RegExp("MSIE ([0-9]{1,}[\.0-9]{0,})");
if (re.exec(ua) != null)
rv = parseFloat( RegExp.$1 );
}
return rv;
}
function checkVersion()
{
var msg = "You're not using Internet Explorer.";
var ver = getInternetExplorerVersion();
if ( ver > -1 )
{
if ( ver >= 6.0 )
msg = "You're using a recent copy of Internet Explorer."
else
msg = "You should upgrade your copy of Internet Explorer.";
}
alert( msg );
}
If you really want to be sure you are using IE and a specific version then you could obviously use IE's conditional tags to only run certain code within IE. It's not really that pretty but at least you can be sure that it is really IE and not some spoofed version.
<script>
var isIE = false;
var version = -1;
</script>
<!--[if IE 6]>
<script>
isIE = true;
version = 6
</script>
<![endif]-->
<!--[if IE 7]>
<script>
isIE = true;
version = 7
</script>
<![endif]-->
It's pretty self explanatory. In IE6 isIE is true and version is 6, In IE7 isIE is true and version is 7 otherwise isIE is false and version is -1
Alternatively you could just roll your own solution using code plagarised from jQuery.
var userAgent = navigator.userAgent.toLowerCase();
var version = (userAgent.match( /.+(?:rv|it|ra|ie)[\/: ]([\d.]+)/ ) || [])[1],
var isIE = /msie/.test( userAgent ) && !/opera/.test( userAgent ),
If you are already using jQuery in a pre-1.9 version AND you don't need to detect IE 11, you can do this:
if (jQuery.browser.msie == true) {
if (jQuery.browser.version == 7.0)
// .. do something for 7.0
else
// .. do something for < 7.0
}
The Navigator object contains all the information about the user's browser:
eg:
var browser=navigator.appName;
var b_version=navigator.appVersion;
var version=parseFloat(b_version);
See:
http://www.w3schools.com/js/js_browser.asp
If you are checking for a certain functionality, you should check for it directly, e.g. if (window.focus) {window.focus();} Browser detection is never reliable enough.
For more details on object vs browser detection, check out this article at Quirksmode.
On the other hand, if the feature you need IS the browser type and version, e.g. for statistical purposes, go with navigator.appName and navigator.appVersion. (Beware though - many less popular browsers masquerade themselves as MSIE 6 or 7, as certain sites block anything that's not IE on the premise that "all the modern browsers are IE, right?" (hint: not anymore).)
So IE8 compatibility view mode reports itself as IE7 even though it doesn't always behave the same. And for that, I give you this monster:
// IE8's "Compatibility mode" is anything but. Oh well, at least it doesn't take 40 lines of code to detect and work around it.
// Oh wait:
/*
* Author: Rob Reid
* CreateDate: 20-Mar-09
* Description: Little helper function to return details about IE 8 and its various compatibility settings either use as it is
* or incorporate into a browser object. Remember browser sniffing is not the best way to detect user-settings as spoofing is
* very common so use with caution.
*/
function IEVersion(){
var _n=navigator,_w=window,_d=document;
var version="NA";
var na=_n.userAgent;
var ieDocMode="NA";
var ie8BrowserMode="NA";
// Look for msie and make sure its not opera in disguise
if(/msie/i.test(na) && (!_w.opera)){
// also check for spoofers by checking known IE objects
if(_w.attachEvent && _w.ActiveXObject){
// Get version displayed in UA although if its IE 8 running in 7 or compat mode it will appear as 7
version = (na.match( /.+ie\s([\d.]+)/i ) || [])[1];
// Its IE 8 pretending to be IE 7 or in compat mode
if(parseInt(version)==7){
// documentMode is only supported in IE 8 so we know if its here its really IE 8
if(_d.documentMode){
version = 8; //reset? change if you need to
// IE in Compat mode will mention Trident in the useragent
if(/trident\/\d/i.test(na)){
ie8BrowserMode = "Compat Mode";
// if it doesn't then its running in IE 7 mode
}else{
ie8BrowserMode = "IE 7 Mode";
}
}
}else if(parseInt(version)==8){
// IE 8 will always have documentMode available
if(_d.documentMode){ ie8BrowserMode = "IE 8 Mode";}
}
// If we are in IE 8 (any mode) or previous versions of IE we check for the documentMode or compatMode for pre 8 versions
ieDocMode = (_d.documentMode) ? _d.documentMode : (_d.compatMode && _d.compatMode=="CSS1Compat") ? 7 : 5;//default to quirks mode IE5
}
}
return {
"UserAgent" : na,
"Version" : version,
"BrowserMode" : ie8BrowserMode,
"DocMode": ieDocMode
}
}
var ieVersion = IEVersion();
var IsIE8 = ieVersion.Version != "NA" && ieVersion.Version >= 8;
This is probably going to get voted down, because it's not directly answering the question, but... You should not be writing browser-specific code. There's very little you can't do while coding for most widely-accepted browsers.
EDIT: The only time I found it useful to have conditional comments was when I needed to include ie6.css or ie7.css.
Well... here is what I came up after thinking for a while. just wanted to find a simple solution.
if (navigator.appName == 'Microsoft Internet Explorer') {
// Take navigator appversion to an array & split it
var appVersion = navigator.appVersion.split(';');
// Get the part that you want from the above array
var verNumber = appVersion[1];
alert(verNumber);
}
It returns ex:- MSIE 10.0, MSIE 9.0, MSIE 8.0
further extend, if you want to check if it's "lower than" or "greater than" IE version, you can slightly modify
if (navigator.appName == 'Microsoft Internet Explorer') {
var appVersion = navigator.appVersion.split(';');
var verNumber = appVersion[1];
// Reaplce "MSIE " from the srting and parse it to integer value
var IEversion = parseInt(verNumber.replace('MSIE ', ''));
if(IEversion <= 9){
alert(verNumber);
}
}
got the base idea from w3schools, hope this will help some one... :D
This is the script I use and it seems to work well enough:
// Returns 0 if the browser is anything but IE
function getIEVersion() {
var ua = window.navigator.userAgent;
var ie = ua.indexOf("MSIE ");
return ((ie > 0) ? parseInt(ua.substring(ie+5, ua.indexOf(".", ie))) : 0);
}
Hope that helps someone...
This should give you more details than you'll want:
var agent = navigator.userAgent;
var msiePattern = /.*MSIE ((\d+).\d+).*/
if( msiePattern.test( agent ) ) {
var majorVersion = agent.replace(msiePattern,"$2");
var fullVersion = agent.replace(msiePattern,"$1");
var majorVersionInt = parseInt( majorVersion );
var fullVersionFloat = parseFloat( fullVersion );
}
As no-one seems to have said it yet:
The test is needed inside a JavaScript function so a conditional comment doesn't seem suitable.
You can easily put a conditional comment — a JScript conditional comment, not an HTML one — inside a function:
function something() {
var IE_WIN= false;
var IE_WIN_7PLUS= false;
/*#cc_on
#if (#_win32)
IE_WIN= true;
#if (#_jscript_version>=5.7)
IE_WIN_7PLUS = true;
#end
#end #*/
...
}
It's more typical to do the test once at global level though, and just check the stored flags thereafter.
CCs are more reliable than sifting through the mess that the User-Agent string has become these days. String matching methods on navigator.userAgent can misidentify spoofing browsers such as Opera.
Of course capability sniffing is much better for cross-browser code where it's possible, but for some cases — usually bug fix workarounds — you do need to identify IE specifically, and CCs are probably the best way to do that today.
<script>
alert("It is " + isIE());
//return ie number as int else return false
function isIE() {
var myNav = navigator.userAgent.toLowerCase();
if (myNav.indexOf('msie') != -1) //ie less than ie11 (6-10)
{
return parseInt(myNav.split('msie')[1]);
}
else
{
//Is the version more than ie11? Then return false else return ie int number
return (!!(myNav.match(/trident/) && !myNav.match(/msie/)) == false)?false : parseInt(myNav.split('rv:')[1].substring(0, 2));
}
}
</script>