I personally love both JavaScript and Python. For this reason, from time to time I like to port functions that are available in Python, over to JavaScript. The following is a port of the expandTabs function.
String.prototype.expandTabs = function(tabSize) {
tabSize = Math.min(Math.max(parseInt(+tabSize || 8), 1), 32);
return this.replace(/^.*\t.*$/gm, function(line) {
var allBefore = "";
return line.replace(/(.*?)(\t+)/g, function(match, before, tabs) {
allBefore += before;
tabs = new Array(1 + tabSize * tabs.length - allBefore.length % tabSize).join(" ");
allBefore += tabs;
return before + tabs;
});
});
};
The biggest difference between this JavaScript version and the Python version is the limitation of a 32 character tab size. If you want to increase the maximum tab size, simply change 32 to something else.
1 Comment
JavaScript – String.prototype.expandTabs() Revisited | Chris West's Blog · January 23, 2012 at 6:11 PM
[…] 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 wanted to have this functionality. Therefore I wrote the following function which is actually shorter and probably faster than the original: […]