我试图移动一些JavaScript代码从MicrosoftAjax到JQuery。我在MicrosoftAjax中使用流行的。net方法的JavaScript等等物,例如String.format(), String.startsWith()等。jQuery中是否有与之对应的函数?
当前回答
到目前为止,所有给出的答案都没有明显的优化,即使用enclosure来初始化一次并存储正则表达式,以供后续使用。
// 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($0) {
var idx = 1 * $0.match(rx2)[0];
return args[idx] !== undefined ? args[idx] : (args[idx] === "" ? "" : $0);
});
}
}());
alert("{0},{0},{{0}}!".format("{X}"));
此外,如果已经存在format()实现,那么所有示例都不尊重它。
其他回答
这违反了DRY原则,但这是一个简洁的解决方案:
var button = '<a href="{link}" class="btn">{text}</a>';
button = button.replace('{text}','Authorize on GitHub').replace('{link}', authorizeUrl);
下面是我的版本,它能够转义'{',并清除那些未分配的占位符。
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);
}
<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>
我有一个活塞,将其添加到字符串原型: string.format 它不仅像其他一些例子一样简短,而且灵活得多。
用法类似于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
另外,增加了对使用名称和对象属性的支持
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
这是Josh发布的函数的一个更快/更简单(和原型)的变体:
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;
};
用法:
'Added {0} by {1} to your collection'.f(title, artist)
'Your balance is {0} USD'.f(77.7)
我经常使用它,所以我把它的别名改成了f,但是你也可以使用更详细的格式。如。“你好,{0}!”.format(名字)