Implemente a função Sprintf/Printf que está disponível na maioria dos idiomas no JavaScript.
http://www.webtoolkit.info/javascript-sprintf.html: uma simulação relativamente completa das funções da função sprintf. Disponível Wildcards formatados:
1. %% - retorne à porcentagem de si mesma
2.%B - número binário
3.%C - ASCII CATERIA
4.%D - Inteiro
5.%F - Número do ponto flutuante
6.%O - número octal
7.%s - string
8.%x - número hexadecimal (formulário de letra minúscula)
9.%x - dígitos hexadecimais (formulário de letra capsular)
As opções disponíveis entre o signo % e os caracteres curinga incluem (por exemplo, % .2f):
1. + (forçando os símbolos + e - a serem exibidos na frente do número como números positivos e negativos. Por padrão, apenas números negativos serão exibidos no símbolo -
2.- (variável esquerda alinhada)
3.0 (use 0 como caractere de preenchimento alinhado à direita)
4. [0-9] (Defina a largura mínima da variável)
5 .. [0-9] (Defina a precisão do ponto flutuante ou o comprimento da corda)
A cópia do código é a seguinte:
/**
*
* Javascript sprintf
* http://www.webtoolkit.info/
*
*
**/
sprintfwrapper = {
init: function () {
if (typeof argumentos == "indefinido") {return null; }
if (argumentos.Length <1) {return null; }
if (typeof argumentos [0]! = "String") {return null; }
if (typeof regexp == "indefinido") {return null; }
var string = argumentos [0];
var exp = novo regexp (/(%([%] | (/-)? (/+|/x20)? (0)? (/d+)? (/. (/d)?)? ([bcdfosxx])))/g);
Var Matches = new Array ();
var strings = new Array ();
var convconting = 0;
var stringPosstart = 0;
var stringposend = 0;
var matchPosEnd = 0;
var newstring = '';
var correspondente = nulo;
while (match = exp.exec (string)) {
if (corresponde [9]) {convcount += 1; }
stringPosstart = matchPosend;
stringposend = exp.LastIndex - corresponde [0] .Length;
strings [strings.length] = string.substring (stringposstart, stringposend);
MatchaSend = exp.LastIndex;
Matches [Matches.Length] = {
Match: Match [0],
Esquerda: Match [3]? Verdadeiro: falso,
sinal: corresponda [4] || '',
PAD: MACH [5] || '',
Min: Match [6] || 0,
Precision: Match [8],
Código: corresponde [9] || '%',
Negativo: Parseint (argumentos [convcount]) <0? Verdadeiro: falso,
Argumento: String (Argumentos [ConvCount])
};
}
strings [strings.length] = string.substring (matchposend);
if (matches.Length == 0) {return string; }
if ((argumentos.Length - 1) <ConvCount) {return null; }
var código = null;
var correspondente = nulo;
var i = null;
for (i = 0; i <matches.length; i ++) {
if (corresponde [i] .code == '%') {substituição = '%'}
caso contrário, se (corresponde [i] .code == 'b') {
corresponde [i] .argument = string (math.abs (parseint (corresponde [i] .argument)). ToString (2));
substituição = sprintfwrapper.convert (corresponde [i], true);
}
caso contrário, se (corresponde [i] .code == 'c') {
corresponde [i] .argument = string (string.fromCharcode (parseint (math.abs (parseint (corresponde [i] .argument)))));
substituição = sprintfwrapper.convert (corresponde [i], true);
}
caso contrário, se (corresponde [i] .code == 'd') {
corresponde [i] .argument = string (math.abs (parseint (corresponde [i] .argument)));
substituição = sprintfwrapper.convert (corresponde [i]);
}
caso contrário, se (corresponde [i] .code == 'f') {
corresponde [i] .argument = string (math.abs (parsefloat (corresponde [i] .argument)). tofixed (corresponde [i] .precision? Matches [i] .precision: 6));
substituição = sprintfwrapper.convert (corresponde [i]);
}
caso contrário, se (corresponde [i] .code == 'o') {
corresponde [i] .argument = string (math.abs (parseint (corresponde [i] .argument)). ToString (8));
substituição = sprintfwrapper.convert (corresponde [i]);
}
caso contrário, se (corresponde [i] .code == 's') {
Matches [i] .argument = corresponde [i] .argument.substring (0, corresponde [i] .Precision? Matches [i] .Precision: Matches [i] .Argument.Length)
substituição = sprintfwrapper.convert (corresponde [i], true);
}
caso contrário, se (corresponde [i] .code == 'x') {
corresponde [i] .argument = string (math.abs (parseint (corresponde [i] .argument)). ToString (16));
substituição = sprintfwrapper.convert (corresponde [i]);
}
caso contrário, se (corresponde [i] .code == 'x') {
corresponde [i] .argument = string (math.abs (parseint (corresponde [i] .argument)). ToString (16));
substituição = sprintfwrapper.convert (corresponde [i]). toupppercase ();
}
outro {
substituição = corresponde [i] .match;
}
newstring += strings [i];
newstring += substituição;
}
newstring += strings [i];
Retornar Newstring;
},
Converter: function (corresponda, Nosign) {
if (nosign) {
match.sign = '';
} outro {
Match.sign = Match.Negative? '-': match.sign;
}
var l = match.min - match.argument.length + 1 - match.sign.length;
var pad = nova matriz (l <0? 0: l) .Join (match.pad);
if (! Match.left) {
if (match.pad == "0" || Nosign) {
Retornar Match.sign + Pad + Match.argument;
} outro {
Retornar Pad + Match.sign + Match.argument;
}
} outro {
if (match.pad == "0" || Nosign) {
Return Match.sign + Match.argument + pad.Replace (/0/g, '');
} outro {
Retornar Match.sign + Match.argument + pad;
}
}
}
}
sprintf = sprintfwrapper.init;
Se você deseja apenas substituir o conteúdo da variável de posição sem formatação adicional, poderá usar o PrintF fornecido nas ferramentas YUI mais simples:
A cópia do código é a seguinte:
Yahoo.tools.printf = function () {
var num = argumentos.Length;
var ostr = argumentos [0];
for (var i = 1; i <num; i ++) {
var Pattern = "// {" + (i-1) + "//}";
var re = novo regexp (padrão, "g");
astr = ostr.replace (re, argumentos [i]);
}
retornar ostr;
}
Ao usá -lo, use {?} Para corresponder.