Skip to content

Instantly share code, notes, and snippets.

@mbjordan
Last active December 18, 2015 15:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mbjordan/5807011 to your computer and use it in GitHub Desktop.
Save mbjordan/5807011 to your computer and use it in GitHub Desktop.
SPrint.js - s[tring]print
// ------------ Tests
var s0,
s1;
// Ordered Array mode
s0 = sprint("This is %s %s call, using an %s in order", "a", "function", "array");
// Ordered|Unordered Obejct Literal mode
s1 = sprint("This is a %s*sw function, %s*ma! You need to %s*ch this out", {
ma: "mang",
sw: "sweet",
ch: "check"
});
console.log(s0);
console.log(s1);
function sprint(str) {
var o, regex;
o = Array.prototype.slice.call(arguments, 1);
regex = /%s\*([a-zA-Z0-9\-_]+)/g;
// Make sure the input is (at least barley) legit;
if (typeof str !== "string" || typeof o !== "object") {
return;
}
if (regex.test(str)) {
str = str.replace(regex, function (found, match) {
return o[0][match];
});
} else {
for (var i = 0; i < o.length; i++) {
str = str.replace(/%s/, o[i]);
}
}
return str;
}

Use

Ordered method:

sprint(string, replacement [, replacement ... ]);

Key->Value Method:

sprint(string, Object);

The object should be a JS Object Litereal.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment