L'équivalent de la Chaîne.format en jQuery

j'essaie de déplacer du code JavaScript de MicrosoftAjax à JQuery. J'utilise les équivalents JavaScript dans MicrosoftAjax des méthodes populaires .net, par exemple String.format (), String.startsWith (), etc. Existe-il des équivalents dans jQuery?

185
demandé sur abatishchev 2009-06-24 18:30:36

20 réponses

le code source pour ASP.NET AJAX est disponible pour votre référence, de sorte que vous pouvez choisir à travers elle et inclure les pièces que vous voulez continuer à utiliser dans un fichier JS séparé. Ou, vous pouvez les porter à jQuery.

Voici la fonction format...

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

et voici les terminaux et les démarreurs avec des fonctions de prototype...

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);
}
187
répondu Josh Stodola 2009-06-24 15:10:35

il s'agit d'une variation plus rapide/plus simple (et prototypique) de la fonction que Josh a affiché:

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

Utilisation:

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

Je l'utilise tellement que je l'ai simplement aliasé en f , mais vous pouvez aussi utiliser le plus verbeux format . par exemple 'Hello {0}!'.format(name)

144
répondu adamJLev 2012-01-23 19:30:30

plusieurs des fonctions ci-dessus (à L'exception de celles de Julian Jelfs) contiennent l'erreur suivante:

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

Ou, pour les variantes qui compter à rebours à partir de la fin de la liste d'arguments:

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

Voici une fonction correcte. C'est une variante prototypique du code de Julian Jelfs, que j'ai fait un peu plus serré:

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

et voici une version légèrement plus avancée de la même, qui vous permet d'échapper à des bretelles par les doubler:

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

cela fonctionne correctement:

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

Voici une autre bonne implémentation par Blair Mitchelmore, avec un tas de jolies fonctionnalités supplémentaires: https://web.archive.org/web/20120315214858/http://blairmitchelmore.com/javascript/string.format

125
répondu gpvos 2014-06-02 14:26:32

fait une fonction de format qui prend soit une collection ou un tableau comme arguments

Utilisation:

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

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

Code:

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];
    });
};
46
répondu ianj 2011-07-01 22:23:44

Il est (un peu) le responsable de l'option: jQuery.validateurs.format .

est livré avec le Plugin de Validation jQuery 1.6 (au moins).

Très similaire au String.Format trouvé dans .NET.

Modifier correction de lien brisé.

36
répondu rsenna 2014-01-02 12:51:55

si vous utilisez le plugin de validation vous pouvez utiliser:

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

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

15
répondu fiestacasey 2012-04-02 11:32:38

bien que ce ne soit pas exactement ce que le Q demandait, j'en ai construit un qui est similaire mais qui utilise des espaces nommés au lieu de numérotés. Personnellement, je préfère avoir des arguments nommés et il suffit d'envoyer un objet comme argument (plus verbeux, mais plus facile à entretenir).

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

voici un exemple d'usage...

alert("Hello {name}".format({ name: 'World' }));
12
répondu Brian 2011-06-21 03:29:11

aucune des réponses présentées jusqu'à présent n'a d'optimisation évidente de l'utilisation de l'enclosure pour initialiser une fois et stocker des expressions régulières, pour des usages ultérieurs.

// 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("151900920") {
            var idx = 1 * "151900920".match(rx2)[0];
            return args[idx] !== undefined ? args[idx] : (args[idx] === "" ? "" : "151900920");
        });
    }
}());

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

de plus, aucun des exemples ne respecte le format() de mise en œuvre s'il en existe déjà un.

6
répondu 2011-08-07 01:03:24

voici le mien:

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

N'est pas à l'épreuve des balles, mais fonctionne si vous l'utilisez raisonnablement.

4
répondu Julian Jelfs 2011-02-04 09:55:12

en utilisant un navigateur moderne, qui prend en charge EcmaScript 2015 (ES6), vous pouvez profiter de template Strings . Au lieu de formater, vous pouvez injecter directement la valeur de la variable:

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

notez que la chaîne de caractères du modèle doit être écrite en cochant (`).

4
répondu david 2016-12-09 04:12:17

voici ma version qui est capable de s'échapper ' { ' , et nettoyer ces supports de place non assignés.

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);
}
2
répondu Feng 2011-02-23 19:22:37

la réponse suivante est probablement la plus efficace, mais elle ne convient qu'à 1 ou 1 mappage d'arguments. Ceci utilise la manière la plus rapide de concaténer les chaînes (similaire à un compilateur de chaînes: array of strings, joined). Ceci est mon propre code. Probablement besoin d'un meilleur séparateur.

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

utiliser comme:

alert(String.format("<a href='~'>~</a>", ["one", "two"]));
2
répondu Skychan 2014-01-03 19:05:33

Maintenant, vous pouvez utiliser "151920920 de Modèle" Littéraux :

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);
2
répondu Arek Kostrzeba 2016-07-24 23:38:33

cela viole le principe sec, mais c'est une solution concise:

var button = '<a href="{link}" class="btn">{text}</a>';
button = button.replace('{text}','Authorize on GitHub').replace('{link}', authorizeUrl);
1
répondu ilyaigpetrov 2015-08-19 01:58:17

bien après la fin de la saison mais j'ai juste regardé les réponses données et ai ma tuppence vaut:

Utilisation:

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

méthode:

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

résultat:

"aalert" is not defined
3.14 3.14 a{2}bc foo
1
répondu RickL 2017-10-18 01:28:30
<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>
0
répondu Kishor Dalwadi 2012-10-27 02:31:34

Je n'ai pas pu obtenir la réponse de Josh Stodola au travail, mais les suivants ont fonctionné pour moi. Remarque l'indication de prototype . (Testé sur IE, FF, Chrome et 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 devrait vraiment être un clone de this pour ne pas être une méthode destructive, mais ce n'est pas vraiment nécessaire.

0
répondu JellicleCat 2014-01-03 19:26:52

S'étendant sur la grande réponse d'adamJLev au-dessus de , voici la version dactylographiée:

// 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;
};
0
répondu Annie 2017-05-23 12:26:24

j'ai un plunker qui l'ajoute à la chaîne prototype: de la chaîne.format Il n'est pas aussi court que quelques autres exemples, mais beaucoup plus souple.

utilisation est similaire à la version 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

également, ajouté le soutien pour l'utilisation des noms et des propriétés d'objet

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
0
répondu ShrapNull 2015-09-14 15:30:44

vous pouvez également fermer le tableau avec des remplacements comme celui-ci.

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

ou vous pouvez essayer bind

'/getElement/_/_/_'.replace(/_/g, (function(_) {return this.ar[this.i++];}).bind({ar: ["invoice", "id", 1337],i: 0}))
0
répondu test30 2016-06-10 02:55:18