Skip to content

Instantly share code, notes, and snippets.

@kbshl
Last active October 30, 2017 18:41
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 kbshl/a8791570cc91938d83cf to your computer and use it in GitHub Desktop.
Save kbshl/a8791570cc91938d83cf to your computer and use it in GitHub Desktop.
Appcelerator Titanium Mobile: Formatting Strings the correct way using printf From http://www.tidev.io/2015/01/26/formatting-strings-the-correct-way-using-an-old-friend-printf/
String.prototype.printf = function (obj) {
var useArguments = false,
_arguments = arguments,
i = -1;
if (typeof _arguments[0] == 'string') {
useArguments = true;
}
if (obj instanceof Array || useArguments) {
return this.replace(/\%s/g, function (a, b) {
i++;
if (useArguments) {
if (typeof _arguments[i] == 'string') {
return _arguments[i];
}
else {
throw new Error('Arguments element is an invalid type');
}
}
return obj[i];
});
}
else {
return this.replace(/{([^{}]*)}/g, function (a, b) {
var r = obj[b];
return (typeof r === 'string' || typeof r === 'number' ? r : a);
});
}
};
var forename = 'Malcolm',
number = 13,
prize = 'Balloon',
message = "Welcome, {name}! you are visitor number {visitor} as visitor number {visitor} you get a {prize}";
Ti.API.info(message.printf({
name: forename,
visitor: number,
prize: prize
}));
// Output: Welcome, Malcolm! you are visitor number 13 as visitor number 13 you get a Balloon
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment