Skip to content

Instantly share code, notes, and snippets.

@mbjordan

mbjordan/sprint-tests.js

Last active Dec 18, 2015
Embed
What would you like to do?
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