I am a self-taught developer with knowledge of Azure, C, C++, C#, Typescript/JavaScript, HTML and CSS along with several databases. Having been working in IT for over 30 years and co-founding and selling a successful company I am now working on products for the TV industry.Follow me on twitter @coderanger, Mastodon @coderanger/@dotnet.social and GitHub

Useful JavaScript String Format

Quite often I need to create a formatted string with padded numbers or other replacement text so to reproduce a useful function like that which is available in C or C++ (and other languages) I decided to create a simple method on the String class to recreate the following function signature:

var message = String.format('Hello %s, the time is %02d:%02d!', name, hour, minute );

Options:

%s    : replace with a string
%5s   : replace with a string padded with spaces to 5 characters in length

%d    : replace with an integer, throws if not a number
%03d  : replace with an integer padded with zeroes to 3 significant figures
%4d   : replace with integer padded with spaces to4 significant figures

%x    : replace with an integer converted to hex, throws if not a number
%X    : replace with an integer converted to upper case hex, throws if not a number
%03x   : replace with an integer converted to hex padded with zeroes to 3 characters in length
%4x  : replace with an integer converted to hex padded with spaces to 4 characters in length

Here is the code, as you can see it uses a useful array method “reduce” which calls the callback function on each element of the array to produce our results:

String.format = function() {  
  var formatArguments = [].slice.call( arguments );
  var formatDefinition = formatArguments.shift();

  function replacer( text, replacement ) {
    var pad = function(value, size, padValue) {
        var s = value+"";
        while (s.length < size) s = padValue + s;
        return s;
      };

    var type = new RegExp( "%([0-9]*)(d|x|X|s)" );
    var matches = type.exec( text );
    console.log ( matches );

    var replacementValue = replacement;
    if( matches && matches.length >= 1 )
    {
      if( matches[2] === "s" )
      {
        replacementValue = pad( replacement, matches[1], " " );
      }
      else if( matches.length > 2 && (matches[2] === "d" || matches[2].toLowerCase() === "x") )
      {
        if( typeof(replacement) !== "number" )
          throw new Error( "Parameter " + formatArguments.length + " '" + replacement + "' is not a number" );

        replacementValue = matches[2] === "x" ? replacement.toString(16) : (matches[2] === "X" ? replacement.toString(16).toUpperCase() : replacement);
        replacementValue = pad( replacementValue, matches[1], matches[1].length > 0 && matches[1][0] === "0" ? "0" : " " );
      }
      text = text.replace(matches[0], replacementValue );
    }

    return text.replace( /%%/, "%" );
  }

  return formatArguments.reduce( replacer, formatDefinition );
};


// Some testing
var name = 'Dan';  
var date = new Date();  
var hour = date.getHours();  
var minute = date.getMinutes();

var message = String.format("Hello '%5s', the time is %s:%s - is %d:%012d - a hex value %x or upper hex %06X as a percentage %d%% as %% are escaped", name, hour, minute, hour, minute, 95, 95, 23 );

console.log(message);

Would result in the following output:

Hello '  Dan', the time is 11:48 - is 11:000000000048 - a hex value 5f or upper hex 00005F as a percentage 23% as % are escaped

Inserting Items into a JavaScript Array

Due to the nature of arrays, inserting an item into an existing array is not a standard method, by you can fake it if you know you have an array which would benefit.

The native method we can use is:

Array.splice( position, numberOfItemsToRemove, item);

So we can now extend the native Array prototype in JavaScript with something more descriptive:

Array.prototype.insertAt = function ( index, item ) {  
  this.splice( index, 0, item );
};

Automate Microsoft Excel using JavaScript

For a project I needed to do, I required a simple JavaScript object where I could automate some Excel functionality, so I created one.

Here it is if anyone else finds it useful…

/*
  Usage:
    var excel = new Excel( "d:\\testfile.xlsx" );

    excel.openFile();

    // Find a named worksheet, delete the first row then save it out as text
    var sheetNum = excel.findWorkSheetNumber( "Sheet 2" );
    if( sheetNum != -1 )
    {
      var ws = excel.getWorkSheet( sheetNum );

      // Delete a row range
      var range = ws.Range( "A1", "AZ2" );
      var row = range.EntireRow;
      row.Delete();

      // Now save this worksheet as unicode text
      var savedTextFile = excel.saveWorkSheet( sheetNum );
    }

    excel.quit();
*/


var Excel = function ( filePath )  
{
  var _filePath = filePath;

  var _fso = new ActiveXObject( "scripting.filesystemobject" );

  var _excel = new ActiveXObject( "Excel.Application" );
  var _wookbooks, _workbook;

  var _xlTextWindows = 20;
  var _xlUnicodeText = 42;
  var _XlSaveAsAccessModexlNoChange = 1;
  var _xlDoNotSaveChanges = 2;

  return {
    openFile: function ()
    {
      _excel.Visible = true;

      _wookbooks = _excel.Workbooks;

      _workbook = _wookbooks.Open( _filePath );
    },

    findWorkSheetNumber: function ( sheetName )
    {
      var sheets = _workbook.Worksheets;

      var total = sheets.Count;
      for ( var u = 1; u <= total ; u++ )
      {
        var ws = sheets.Item( u );

        ws.Activate();

        var worksheetName = ws.Name;
        if ( worksheetName.toLowerCase() == sheetName.toLowerCase() )
          return u;
      }

      // Not found
      return -1;
    },

    getWorkSheet: function ( sheetNum )
    {
      var sheets = _workbook.Worksheets;

      var ws = sheets.Item( sheetNum );
      ws.Activate();

      return ws;
    },

    trimColumnData: function( str )
    {
      str = str.trim();
      if ( str.length > 0 && str.charAt( 0 ) == "\\"" && str.charAt( str.length - 1 ) == "\\"" )
      {
        str = str.substring( 1, str.length - 1 ).trim();
      }

      return str;
    },

    saveWorkSheet: function ( sheetNum )
    {
      var sheets = _workbook.Worksheets;

      var ws = sheets.Item( sheetNum );
      ws.Activate();

      var worksheetName = ws.Name;

      var saveName = _filePath + "-" + sheetNum + "-(" + worksheetName + ").txt";
      saveName = saveName.replace( /\\?/g, "" );

      // Delete old file
      if ( _fso.fileExists( saveName ) )
      {
        _fso.DeleteFile( saveName );
      }

      _workbook.SaveAs( saveName, _xlUnicodeText, "", "", false, false, _XlSaveAsAccessModexlNoChange );

      return saveName;
    },

    saveAllWorkSheets: function ()
    {
      var sheets = _workbook.Worksheets;

      var total = sheets.Count;
      var sheets = [];
      for ( var u = 1; u <= total; u++ )
      {
        sheets.push( saveWorkSheet( u ) );
      }
      return sheets;
    },

    quit: function ()
    {
      _workbook.Close( false );

      _excel.Quit();
    }
  }
}

Detecting Retina Screens Server-Side

To improve the speed of loading the site I work on at http://digiguide.tv, I would prefer to load retina images into the HTML code from the beginning instead of altering them after the fact using JavaScript. Unfortunately I cannot use CSS media queries as the images are dynamic and determined by the server code.

So what to do? it appears there is no user-agent information for pixel density or device model which seems to be a major oversight and wouldn’t have taken much to just add. So we are stuck with the only two options mentioned above.

A possible solution is to use JavaScript to set a cookie (session or permanent) on very first page load and use this on subsequent page loads, and if you need the first page to use retina images perhaps do a redirect if the cookie doesn’t exist.

So we are left with this bit of code client-side:

 
var isRetina = readCookie( "isretina" );  
if( !isRetina ) {  
  var modern_media_query = window.matchMedia( "screen and (-webkit-min-device-pixel-ratio:2)");     
  if( modern_media_query.matches ) {
    // set our cookie
    var expires = new Date().toUTCString();
    document.cookie = "isretina=true; "+ expires +"; path=/";

    // optionally reload page...
  }
}

function readCookie(name) {  
  var nameEQ = name + "=";
  var ca = document.cookie.split(';');
  for(var i=0;i < ca.length;i++) {
    var c = ca[i];
    while (c.charAt(0)==' ') c = c.substring(1,c.length);
    if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
  }
  return null;
}

And on the server we can just check for the ‘isretina’ cookie value to determine which images to use.

Useful JavaScript Date Methods

I needed an easy way to add or subtract months from a JavaScript date and have it do it correctly for situations like the end of the month where the new month has different days, but also for it to roll backward/forward to a different year when necessary.

Here is a simple solution which extends the built-in Date class:

Date.prototype.addMonths = function( months )  
{
    var monthsTotal = this.getMonth() + this.getYear() * 12 + months;
    var day = this.getDate();
    var year = monthsTotal / 12;
    var month = monthsTotal % 12;

    var maxDays = this.getDaysInMonth( year, month );
    if( day > maxDays )
    {
        day = maxDays;
        OutputLog( "day: " + day );
    }

    this.setYear( year );
    this.setDate( day );
    this.setMonth( month );
}

Date.prototype.getDaysInMonth = function( year, month )  
{
    var days = [ 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 ];

    //
    //  Check for leap year
    if( month == 1 && year % 4 == 0 && ( year % 100 || year % 400 == 0 ) )
    {
        return 29;
    }

    return days[ month ];
}

You would use these new methods as follows:

var test = new Date( 2011, 2, 30, 06, 10, 11 );  
test.addMonths( -1 );  
alert( test);

test = new Date( 2011, 1, 30, 06, 10, 11 );  
test.addMonths( 12 );  
alert( test );

And here is an additional useful method to provide a way of returning the month name:

Date.prototype.getMonthName = function()  
{
    var names = [ "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" ];

    return names[ this.getMonth() ];
}

Detect if AdBlock is Running

Here is a bit of useful code to try and detect if AdBlock is running…

  
// Code written and copyright by www.tweaktown.com
// You will have to check with them whether you can use it...
setTimeout('detect_abp()', 10000);

var isFF = (navigator.userAgent.indexOf("Firefox") > -1) ? true : false;
var hasABP = false;

function detect_abp()
{
    if( isFF )
    {
        if( Components.interfaces.nsIAdblockPlus != undefined )
        {
            hasABP = true;
        }
        else
        {
            var AbpImage = document.createElement("IMG");
            AbpImage.id = 'abp_detector';
            AbpImage.src = '/textlink-ads.jpg';
            AbpImage.style.width = '0px';
            AbpImage.style.height = '0px';
            AbpImage.style.top = '-1000px';
            AbpImage.style.left = '-1000px';
            document.body.appendChild( AbpImage );
            hasABP = (document.getElementById('abp_detector').style.display == 'none');

            var e = document.getElementsByTagName("iframe");
            for ( var i = 0; i < e.length; i++ )
            {
                if( e[i].clientHeight == 0 )
                {
                    hasABP = true;
                }
            }
        }

        if( hasABP == true )
        {
            history.go(1);

            // Jump to somewhere useful, a good example is at
            // www.tweaktown.com/supportus.html
            
        }
    }
}

Javascript cool feature of the day: on Browser Ready

From: http://www.fearthecowboy.com/2007/02/javascript-cool-feature-of-day-on.html

A nice little one-liner script you can use in your HMTL page to run some a function when the browser is done loading the HTML.

I have been using this cool little snippet for a while, something I factored down for my own purposes, and tucked away in my little bag of tricks. I didn’t realize that others’ were not using something similar to this, (I saw a spate of posts where people were using document.write)[SHUDDER!]. So, I’m going to post it, and let the world rejoice:

var myinit = document.addEventListener ? document.addEventListener("DOMContentLoaded", function(){myinit();}, false): setInterval( function(){if (/loaded|complete/.test( document.readyState )){ clearInterval(myinit);myinit(); } }, 10);

Works in IE, FireFox, and Safari. Probably others, as I think most browsers support one of the two methods for bootstrapping an init function.

To use it, just replace the two myinit() calls with whatever you want to run, and the replace the myinit variables to something that’ll be unique to you. I’d comment on my crazy desire to overload the living tar out of the ternary operator in javascript, but that’d be redundant.