C # a le très puissant String.Format()
pour remplacer des éléments comme {0}
par des paramètres. JavaScript a-t-il un équivalent?
Essayez sprintf () pour javascript .
Ou
// First, checks if it isn't implemented yet. if (!String.prototype.format) { String.prototype.format = function() { var args = arguments; return this.replace(/{(\d+)}/g, function(match, number) { return typeof args[number] != 'undefined' ? args[number] : match ; }); }; } "{0} is dead, but {1} is alive! {0} {2}".format("ASP", "ASP.NET")
Les deux réponses tirées de JavaScript équivalent à printf / string.format
J'utilise:
String.prototype.format = function() { var s = this, i = arguments.length; while (i--) { s = s.replace(new RegExp('\\{' + i + '\\}', 'gm'), arguments[i]); } return s; };
Utilisation: "Hello {0}".format("World");
Je l'ai trouvé à Equivalent de String.format dans JQuery
ACTUALISÉ:
Dans ES6 / ES2015, vous pouvez utiliser des modèles de chaînes par exemple
'use strict'; let firstName = 'John', lastName = 'Smith'; console.log(`Full Name is ${firstName} ${lastName}`); // or console.log(`Full Name is ${firstName + ' ' + lastName}');
Je l'ai créé il y a longtemps, question connexe
String.Format = function (b) { var a = arguments; return b.replace(/(\{\{\d\}\}|\{\d\})/g, function (b) { if (b.substring(0, 2) == "{{") return b; var c = parseInt(b.match(/\d/)[0]); return a[c + 1] }) };
Basé sur @ Vlad Bezden répondre J'utilise ce code légèrement modifié parce que je préfère les espaces réservés nommés:
String.prototype.format = function(placeholders) { var s = this; for(var propertyName in placeholders) { var re = new RegExp('{' + propertyName + '}', 'gm'); s = s.replace(re, placeholders[propertyName]); } return s; };
usage:
"{greeting} {who}!".format({greeting: "Hello", who: "world"})
String.prototype.format = function(placeholders) { var s = this; for(var propertyName in placeholders) { var re = new RegExp('{' + propertyName + '}', 'gm'); s = s.replace(re, placeholders[propertyName]); } return s; }; $("#result").text("{greeting} {who}!".format({greeting: "Hello", who: "world"}));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="result"></div>