在JavaScript中有一个C#String.Format()等价物吗?

C#具有非常强大的String.Format() ,用参数replace{0}等元素。 JavaScript是否具有相同的function?

尝试sprintf()为JavaScript 。

要么

 // 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") 

这两个答案从JavaScript相当于printf / string.format

我在用:

 String.prototype.format = function() { var s = this, i = arguments.length; while (i--) { s = s.replace(new RegExp('\\{' + i + '\\}', 'gm'), arguments[i]); } return s; }; 

用法: "Hello {0}".format("World");

我发现它在jQuery的String.format等价

更新:

在ES6 / ES2015中,您可以使用string模板

 'use strict'; let firstName = 'John', lastName = 'Smith'; console.log(`Full Name is ${firstName} ${lastName}`); // or console.log(`Full Name is ${firstName + ' ' + lastName}'); 

我很早以前就创build了它, 相关的问题

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

基于@ Vlad Bezden答案我使用这个稍微修改的代码,因为我更喜欢命名的占位符:

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

用法:

 "{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>