Showing posts with label javascript. Show all posts
Showing posts with label javascript. Show all posts

Sunday, May 18, 2008

(str)tr for JavaScript

I couldn't find a function resembling Ruby's tr or PHP's strtr in JavaScript, so I created one. Here's the code:


function tr(str, from, to) {
var subst;
for (i = 0; i < from.length; i++) {
subst = (to[i]) ? to[i] : to[to.length-1];
str = str.replace(new RegExp(str[str.indexOf(from[i])], 'g'), subst);
}
return str;
}

Saturday, November 24, 2007

Easiest way to check IE version with JavaScript

Alright, so I needed a easy way to execute custom JavaScript for clients using versions of IE lower than 7. All the scripts Google showed me were really huge and quite outdated. So I took what I found, and turned it into something really lightweight. Note that this is just a quick hack, but so far it seems to be enough for my needs.

Code:


var Browser = {
Version: function() {
var version = 999; // we assume a sane browser
if (navigator.appVersion.indexOf("MSIE") != -1)
// bah, IE again, lets downgrade version number
version = parseFloat(navigator.appVersion.split("MSIE")[1]);
return version;
}
}


Which enables me to do stuff like this:


if (Browser.Version() < 7) {
... // if client is using IE6 or lower, run this code
}


..or this:


if (Browser.Version() >= 7) {
... // if client is using IE7 or a sane browser, run this code
}


It will simply return 999 if the browser is non-IE. Is it safe to assume that navigator.appVersion always will contain "MSIE" in uppercase?