Created
April 25, 2014 20:45
-
-
Save creage/11302690 to your computer and use it in GitHub Desktop.
$.format
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
(function ($, window, document, undefined) { | |
$.extend({ | |
/** | |
* Format at string using .NET C# syntax | |
$.format("test {0} and {1}", "is cool", "and passed"); | |
$.format("test {1} and {0}", ["is cool", "and passed"]); | |
*/ | |
format: (function () { | |
var iterate = function (txt, replacements) { | |
for (var i = 0, l = replacements.length; i < l; i++) { | |
txt = txt.replace(new RegExp("\\{" + (i) + "\\}", "g"), replacements[i]); | |
} | |
return txt; | |
}; | |
return function () { | |
if (arguments.length) { | |
var args = arguments, | |
text = Array.prototype.splice.apply(args, [0, 1])[0]; | |
if ($.isArray(args[0])) { | |
text = iterate(text, args[0]); | |
} else { // if first parameter is not an object it can be the first of a series of variant inline parameters. | |
text = iterate(text, args); | |
} | |
return text; | |
} else { | |
return this; | |
} | |
}; | |
})() | |
}); | |
}(jQuery, window, document)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment