konstantinbueschel
1/27/2015 - 9:50 AM

Appcelerator Titanium Mobile: Formatting Strings the correct way using printf From http://www.tidev.io/2015/01/26/formatting-strings-the-co

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/

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
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);
        });
    }
};