Pregunta

Estoy tratando de mover un código JavaScript de MicrosoftAjax a JQuery. Utilizo los equivalentes de JavaScript en MicrosoftAjax de los métodos populares .net, p. String.format (), String.startsWith (), etc. ¿Hay equivalentes en jQuery?

¿Fue útil?

Solución

El el código fuente de ASP.NET AJAX está disponible para su referencia, por lo que puede seleccionarlo e incluir las partes que desea continuar usando en un archivo JS separado. O puede portarlos a jQuery.

Aquí está la función de formato ...

String.format = function() {
  var s = arguments[0];
  for (var i = 0; i < arguments.length - 1; i++) {       
    var reg = new RegExp("\\{" + i + "\\}", "gm");             
    s = s.replace(reg, arguments[i + 1]);
  }

  return s;
}

Y aquí están los extremosCon y comienzaCon funciones prototipo ...

String.prototype.endsWith = function (suffix) {
  return (this.substr(this.length - suffix.length) === suffix);
}

String.prototype.startsWith = function(prefix) {
  return (this.substr(0, prefix.length) === prefix);
}

Otros consejos

Esta es una variación más rápida / simple (y prototípica) de la función que Josh publicó:

String.prototype.format = String.prototype.f = function() {
    var s = this,
        i = arguments.length;

    while (i--) {
        s = s.replace(new RegExp('\\{' + i + '\\}', 'gm'), arguments[i]);
    }
    return s;
};

Uso:

'Added {0} by {1} to your collection'.f(title, artist)
'Your balance is {0} USD'.f(77.7) 

Utilizo esto tanto que solo lo alias a f , pero también puede usar el formato más detallado. p.ej. 'Hola {0}!'. formato (nombre)

Muchas de las funciones anteriores (excepto las de Julian Jelfs) contienen el siguiente error:

js> '{0} {0} {1} {2}'.format(3.14, 'a{2}bc', 'foo');
3.14 3.14 afoobc foo

O, para las variantes que cuentan hacia atrás desde el final de la lista de argumentos:

js> '{0} {0} {1} {2}'.format(3.14, 'a{0}bc', 'foo');
3.14 3.14 a3.14bc foo

Aquí hay una función correcta. Es una variante prototípica del código de Julian Jelfs, que hice un poco más estricto:

String.prototype.format = function () {
  var args = arguments;
  return this.replace(/\{(\d+)\}/g, function (m, n) { return args[n]; });
};

Y aquí hay una versión un poco más avanzada de la misma, que le permite escapar de las llaves duplicándolas:

String.prototype.format = function () {
  var args = arguments;
  return this.replace(/\{\{|\}\}|\{(\d+)\}/g, function (m, n) {
    if (m == "{{") { return "{"; }
    if (m == "}}") { return "}"; }
    return args[n];
  });
};

Esto funciona correctamente:

js> '{0} {{0}} {{{0}}} {1} {2}'.format(3.14, 'a{2}bc', 'foo');
3.14 {0} {3.14} a{2}bc foo

Aquí hay otra buena implementación de Blair Mitchelmore, con un montón de buenas características adicionales: https://web.archive.org/web/20120315214858/http://blairmitchelmore.com/javascript/string.format

Hizo una función de formato que toma una colección o una matriz como argumentos

Uso:

format("i can speak {language} since i was {age}",{language:'javascript',age:10});

format("i can speak {0} since i was {1}",'javascript',10});

Código:

var format = function (str, col) {
    col = typeof col === 'object' ? col : Array.prototype.slice.call(arguments, 1);

    return str.replace(/\{\{|\}\}|\{(\w+)\}/g, function (m, n) {
        if (m == "{{") { return "{"; }
        if (m == "}}") { return "}"; }
        return col[n];
    });
};

Hay una opción (algo) oficial: jQuery.validator.format .

Viene con jQuery Validation Plugin 1.6 (al menos).
Muy similar al String.Format que se encuentra en .NET.

Editar Se corrigió el enlace roto.

Si está utilizando el complemento de validación, puede usar:

jQuery.validator.format (" {0} {1} " ;, " cool " ;, " formatting ") = 'cool formatting'

http://docs.jquery.com/Plugins/Validation/jQuery.validator.format #templateargumentargumentN ...

Aunque no es exactamente lo que estaba pidiendo la Q, he creado uno que es similar pero usa marcadores de posición con nombre en lugar de numerados. Personalmente prefiero tener argumentos con nombre y simplemente enviar un objeto como argumento (más detallado, pero más fácil de mantener).

String.prototype.format = function (args) {
    var newStr = this;
    for (var key in args) {
        newStr = newStr.replace('{' + key + '}', args[key]);
    }
    return newStr;
}

Aquí hay un ejemplo de uso ...

alert("Hello {name}".format({ name: 'World' }));

Ninguna de las respuestas presentadas hasta ahora no tiene una optimización obvia del uso del gabinete para inicializar una vez y almacenar expresiones regulares, para usos posteriores.

// DBJ.ORG string.format function
// usage:   "{0} means 'zero'".format("nula") 
// returns: "nula means 'zero'"
// place holders must be in a range 0-99.
// if no argument given for the placeholder, 
// no replacement will be done, so
// "oops {99}".format("!")
// returns the input
// same placeholders will be all replaced 
// with the same argument :
// "oops {0}{0}".format("!","?")
// returns "oops !!"
//
if ("function" != typeof "".format) 
// add format() if one does not exist already
  String.prototype.format = (function() {
    var rx1 = /\{(\d|\d\d)\}/g, rx2 = /\d+/ ;
    return function() {
        var args = arguments;
        return this.replace(rx1, function(<*>) {
            var idx = 1 * <*>.match(rx2)[0];
            return args[idx] !== undefined ? args[idx] : (args[idx] === "" ? "" : <*>);
        });
    }
}());

alert("{0},{0},{{0}}!".format("{X}"));

Además, ninguno de los ejemplos respeta la implementación de formato () si ya existe uno.

Utilizando un navegador moderno, que admite EcmaScript 2015 (ES6), puede disfrutar de Cadenas de plantilla . En lugar de formatear, puede inyectarle directamente el valor de la variable:

var name = "Waleed";
var message = `Hello ${name}!`;

Tenga en cuenta que la cadena de la plantilla debe escribirse utilizando ticks de retroceso (`).

Aquí está el mío:

String.format = function(tokenised){
        var args = arguments;
        return tokenised.replace(/{[0-9]}/g, function(matched){
            matched = matched.replace(/[{}]/g, "");
            return args[parseInt(matched)+1];             
        });
    }

No es a prueba de balas, pero funciona si lo usa con sensatez.

Ahora puede usar Template Literals :

var w = "the Word";
var num1 = 2;
var num2 = 3;

var long_multiline_string = `This is very long
multiline templete string. Putting somthing here:
${w}
I can even use expresion interpolation:
Two add three = ${num1 + num2}
or use Tagged template literals
You need to enclose string with the back-tick (\` \`)`;

console.log(long_multiline_string);

Pasado el final de la temporada, pero acabo de ver las respuestas que me dieron y mi tuppence vale la pena:

Uso:

var one = strFormat('"{0}" is not {1}', 'aalert', 'defined');
var two = strFormat('{0} {0} {1} {2}', 3.14, 'a{2}bc', 'foo');

Método:

function strFormat() {
    var args = Array.prototype.slice.call(arguments, 1);
    return arguments[0].replace(/\{(\d+)\}/g, function (match, index) {
        return args[index];
    });
}

Resultado:

"aalert" is not defined
3.14 3.14 a{2}bc foo

Aquí está mi versión que puede escapar de '{' y limpiar esos marcadores de posición no asignados.

function getStringFormatPlaceHolderRegEx(placeHolderIndex) {
    return new RegExp('({)?\\{' + placeHolderIndex + '\\}(?!})', 'gm')
}

function cleanStringFormatResult(txt) {
    if (txt == null) return "";

    return txt.replace(getStringFormatPlaceHolderRegEx("\\d+"), "");
}

String.prototype.format = function () {
    var txt = this.toString();
    for (var i = 0; i < arguments.length; i++) {
        var exp = getStringFormatPlaceHolderRegEx(i);
        txt = txt.replace(exp, (arguments[i] == null ? "" : arguments[i]));
    }
    return cleanStringFormatResult(txt);
}
String.format = function () {
    var s = arguments[0];
    if (s == null) return "";

    for (var i = 0; i < arguments.length - 1; i++) {
        var reg = getStringFormatPlaceHolderRegEx(i);
        s = s.replace(reg, (arguments[i + 1] == null ? "" : arguments[i + 1]));
    }
    return cleanStringFormatResult(s);
}

La siguiente respuesta es probablemente la más eficiente, pero tiene la advertencia de que solo es adecuada para asignaciones de argumentos 1 a 1. Esto utiliza la forma más rápida de concatenar cadenas (similar a un generador de cadenas: matriz de cadenas, unidas). Este es mi propio código. Sin embargo, probablemente necesite un mejor separador.

String.format = function(str, args)
{
    var t = str.split('~');
    var sb = [t[0]];
    for(var i = 0; i < args.length; i++){
        sb.push(args[i]);
        sb.push(t[i+1]);
    }
    return sb.join("");
}

Úselo como:

alert(String.format("<a href='~'>~</a>", ["one", "two"]));

Esto viola el principio DRY, pero es una solución concisa:

var button = '<a href="{link}" class="btn">{text}</a>';
button = button.replace('{text}','Authorize on GitHub').replace('{link}', authorizeUrl);
<html>
<body>
<script type="text/javascript">
   var str="http://xyz.html?ID={0}&TId={1}&STId={2}&RId={3},14,480,3,38";
   document.write(FormatString(str));
   function FormatString(str) {
      var args = str.split(',');
      for (var i = 0; i < args.length; i++) {
         var reg = new RegExp("\\{" + i + "\\}", "");             
         args[0]=args[0].replace(reg, args [i+1]);
      }
      return args[0];
   }
</script>
</body>
</html>

No pude conseguir que la respuesta de Josh Stodola funcionara, pero lo siguiente funcionó para mí. Tenga en cuenta la especificación de prototype . (Probado en IE, FF, Chrome y Safari):

String.prototype.format = function() {
    var s = this;
    if(t.length - 1 != args.length){
        alert("String.format(): Incorrect number of arguments");
    }
    for (var i = 0; i < arguments.length; i++) {       
        var reg = new RegExp("\\{" + i + "\\}", "gm");
        s = s.replace(reg, arguments[i]);
    }
    return s;
}

s realmente debería ser un clon de this para no ser un método destructivo, pero no es realmente necesario.

Ampliando la gran respuesta de adamJLev arriba , aquí está la versión de TypeScript:

// Extending String prototype
interface String {
    format(...params: any[]): string;
}

// Variable number of params, mimicking C# params keyword
// params type is set to any so consumer can pass number
// or string, might be a better way to constraint types to
// string and number only using generic?
String.prototype.format = function (...params: any[]) {
    var s = this,
        i = params.length;

    while (i--) {
        s = s.replace(new RegExp('\\{' + i + '\\}', 'gm'), params[i]);
    }

    return s;
};

Tengo un plunker que lo agrega al prototipo de cadena: string.format No es tan corto como algunos de los otros ejemplos, sino que es mucho más flexible.

El uso es similar a la versión de C #:

var str2 = "Meet you on {0}, ask for {1}";
var result2 = str2.format("Friday", "Suzy"); 
//result: Meet you on Friday, ask for Suzy
//NB: also accepts an array

Además, se agregó soporte para usar nombres & amp; propiedades de objeto

var str1 = "Meet you on {day}, ask for {Person}";
var result1 = str1.format({day: "Thursday", person: "Frank"}); 
//result: Meet you on Thursday, ask for Frank

También puede cerrar la matriz con reemplazos como este.

var url = '/getElement/_/_/_'.replace(/_/g, (_ => this.ar[this.i++]).bind({ar: ["invoice", "id", 1337],i: 0}))
> '/getElement/invoice/id/1337

o puede intentar bind

'/getElement/_/_/_'.replace(/_/g, (function(_) {return this.ar[this.i++];}).bind({ar: ["invoice", "id", 1337],i: 0}))
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top