Last active
December 20, 2015 03:19
-
-
Save ianpgall/6062595 to your computer and use it in GitHub Desktop.
JavaScript function to format strings with the format {#}
This file contains hidden or 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
var Format = (function () { | |
"use strict"; | |
var refToString, toString, re, slice, ret; | |
refToString = {}.toString; | |
toString = function (p) { | |
return refToString.call(p); | |
}; | |
re = /\{(\d+)\}/g; | |
slice = function (args, start) { | |
var arr, i, j, cur; | |
start = start || 0; | |
arr = []; | |
for (i = start, j = args.length; i < j; i++) { | |
cur = args[i]; | |
arr.push(cur); | |
} | |
return arr; | |
}; | |
ret = function (str, args) { | |
if (toString(args) !== "[object Object]") { | |
args = slice(arguments, 1); | |
} | |
return str.replace(re, function (match, $1) { | |
var arg = args[$1]; | |
return arg === undefined ? match : arg; | |
}); | |
}; | |
return ret; | |
}()); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment