我想要一个模仿python .format()函数的javascript函数,就像
一样.format(*args, **kwargs)
之前的问题为' .format(* args)提供了一个可能的(但不是完整的)解决方案
JavaScript equivalent to printf/string.format
我希望能够做到
"hello {} and {}".format("you", "bob"
==> hello you and bob
"hello {0} and {1}".format("you", "bob")
==> hello you and bob
"hello {0} and {1} and {a}".format("you", "bob",a="mary")
==> hello you and bob and mary
"hello {0} and {1} and {a} and {2}".format("you", "bob","jill",a="mary")
==> hello you and bob and mary and jill
我意识到这是一个很高的订单,但也许在某个地方有一个包含关键字参数的完整(或至少部分)解决方案。
哦,我听说AJAX和JQuery可能有这方面的方法,但我希望能够在没有这些开销的情况下完成。
特别是,我希望能够将其与google doc的脚本一起使用。
由于
答案 0 :(得分:12)
更新:如果您使用的是ES6,则模板字符串的工作方式与String.format
非常相似:https://developers.google.com/web/updates/2015/01/ES6-Template-Strings
如果没有,下面适用于上述所有情况,其语法与python的String.format
方法非常相似。下面的测试用例。
String.prototype.format = function() {
var args = arguments;
this.unkeyed_index = 0;
return this.replace(/\{(\w*)\}/g, function(match, key) {
if (key === '') {
key = this.unkeyed_index;
this.unkeyed_index++
}
if (key == +key) {
return args[key] !== 'undefined'
? args[key]
: match;
} else {
for (var i = 0; i < args.length; i++) {
if (typeof args[i] === 'object' && typeof args[i][key] !== 'undefined') {
return args[i][key];
}
}
return match;
}
}.bind(this));
};
// Run some tests
$('#tests')
.append(
"hello {} and {}<br />".format("you", "bob")
)
.append(
"hello {0} and {1}<br />".format("you", "bob")
)
.append(
"hello {0} and {1} and {a}<br />".format("you", "bob", {a:"mary"})
)
.append(
"hello {0} and {1} and {a} and {2}<br />".format("you", "bob", "jill", {a:"mary"})
);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="tests"></div>
答案 1 :(得分:-1)
这应该与python的format
类似,但是对于具有命名键的对象,它也可以是数字。
String.prototype.format = function( params ) {
return this.replace(
/\{(\w+)\}/g,
function( a,b ) { return params[ b ]; }
);
};
console.log( "hello {a} and {b}.".format( { a: 'foo', b: 'baz' } ) );
//^= "hello foo and baz."