Last active
October 30, 2017 18:41
-
-
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/
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
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); | |
}); | |
} | |
}; |
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
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