C#具有非常强大的String.Format()
,用于使用参数替换{0}
等元素。 JavaScript有同等效力吗?
答案 0 :(得分:77)
或者
// 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")
答案 1 :(得分:30)
我正在使用:
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");
我在Equivalent of String.format in JQuery
找到了它更新:
在ES6 / ES2015中,您可以使用string templating作为实例
'use strict';
let firstName = 'John',
lastName = 'Smith';
console.log(`Full Name is ${firstName} ${lastName}`);
// or
console.log(`Full Name is ${firstName + ' ' + lastName}');
答案 2 :(得分:14)
基于@ 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>
&#13;
答案 3 :(得分:13)
我很久以前创建了它,related question
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]
})
};