New & Improved Definition

Last year I wrote a version of this function which was to mimic the Python expandtabs function. The funny thing is I didn’t remember that I wrote the function in the first place. Therefore while working on a project, I wrote the following function which is actually shorter and faster than the original:

String.prototype.expandTabs = function(tabSize) {
  var spaces = (new Array((tabSize = tabSize || 8 ) + 1)).join(" ");
  return this.replace(/([^\r\n\t]*)\t/g, function(a, b) {
    return b + spaces.slice(b.length % tabSize);

Minimum Tab Size

If for some reason the above function, although it mimics my previous version (except it doesn’t limit the tab size to 32), is lacking in your mind because it doesn’t provide a way of specifying the minimum tabSize, you can alternatively use the following function definition:

String.prototype.expandTabs = function(tabSize, minTabSize) {
  tabSize = tabSize || 8;
  minTabSize = minTabSize || 1;
  var spaces = (new Array(Math.ceil((minTabSize - 1) / tabSize) * tabSize + tabSize + 1)).join(" ");
  return this.replace(/([^\r\n\t]*)\t/g, function(a, b) {
    return b + spaces.slice(0, Math.ceil((b.length + minTabSize) / tabSize) * tabSize - b.length);

Although the above definition is more complete, I feel like there is a better calculation for the amount of spaces that I am simply overlooking. All-in-all, I am happy with both of these newer versions of String.prototype.expandTabs(). I guess having a bad memory has its advantages at times. šŸ˜‰

Leave a Reply

Your email address will not be published. Required fields are marked *