JavaScript 中是否有等效的 C# String.Format()?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18405736/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Is there a C# String.Format() equivalent in JavaScript?
提问by David Thielen
C# has the really powerful String.Format()
for replacing elements like {0}
with parameters. Does JavaScript have an equivalent?
C# 具有非常强大String.Format()
的替换元素(如{0}
参数)的能力。JavaScript 有等价物吗?
回答by Scott
Or
或者
// 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")
Both answers pulled from JavaScript equivalent to printf/string.format
从JavaScript 中提取的两个答案都相当于 printf/string.format
回答by Vlad Bezden
I am using:
我在用:
String.prototype.format = function() {
var s = this,
i = arguments.length;
while (i--) {
s = s.replace(new RegExp('\{' + i + '\}', 'gm'), arguments[i]);
}
return s;
};
usage: "Hello {0}".format("World");
用法: "Hello {0}".format("World");
I found it at Equivalent of String.format in JQuery
我在 JQuery 中的 String.format 等效处找到了它
UPDATED:
更新:
In ES6/ES2015 you can use string templatingfor instance
在ES6 / ES2015你可以使用字符串模板,例如
'use strict';
let firstName = 'John',
lastName = 'Smith';
console.log(`Full Name is ${firstName} ${lastName}`);
// or
console.log(`Full Name is ${firstName + ' ' + lastName}');
回答by t3chb0t
Based on @Vlad Bezdenanswer I use this slightly modified code because I prefer named placeholders:
基于@ 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;
};
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>
回答by BrunoLM
I created it a long time ago, 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]
})
};