javaScript printf

Function similar to that in other languages, replaces wildcards in a text string with the values of an array. Example of use:
cad2="%1 changed with %2".printf(["text","printf"]);

Function

String.prototype.printf=function(a,c){
    if(c==undefined){c="%"}
    var b=this;
    for(var d=a.length;d>0;d--){
      b=b.split(c+(d)).join(a[d-1])
    }
    return b
};

Parameters

  • a

    Array, mandatory value. Replace the text string ‘%1’ for the first value of this array, ‘%2’ for the second and so on. The pattern ‘%’ can be replaced by any other with the second parameter passed to the function.
    Example:
    days=["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"];
    alert ("Today is %2, March 12, 2013.".printf(days));
  • c

    Wildcard character, optional value, default ‘%’ if we do not pass any value. Example:
    alert("Today is $2, March 12, 2013.".printf(days,'$'));
    

Leave a Reply

Your email address will not be published. Required fields are marked *