Last active
August 29, 2015 14:23
-
-
Save neatnick/2733b760a99ca1285e12 to your computer and use it in GitHub Desktop.
Python-like string formatting for JavaScript.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Array.prototype.flatten = function() { | |
return this.reduce(function(prev, cur) { | |
var more = [].concat(cur).some(Array.isArray); | |
return prev.concat(more ? cur.flatten() : cur); | |
},[]); | |
}; | |
String.prototype.format = function () { | |
var content = this; | |
// regular for loop would probably be more efficient than the forEach | |
Array.prototype.slice.call(arguments).flatten().forEach(function (item, index) { | |
var pattern = '\\{' + index + '\\}', | |
re = new RegExp(pattern, "g"); | |
content = content.replace(re, item); | |
}); | |
return content; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment