Ordered method:
sprint(string, replacement [, replacement ... ]);
Key->Value Method:
sprint(string, Object);
The object should be a JS Object Litereal.
// ------------ 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; | |
} |