【发布时间】:2012-11-18 08:01:14
【问题描述】:
我想要一个模仿 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 的脚本一起使用。
谢谢
【问题讨论】:
-
嗯,对这个答案很感兴趣,关注。
-
没有内置任何东西,尽管实现起来很简单(对于一些,但不是全部,因为 JavaScript 没有“命名参数”并且指定索引手册不一样,提供的案例) .搜索“javascript printf”以获取一些潜在客户。
-
我不相信 Javascript 默认有这样的东西。您最好尝试使用 Javascript 框架或库。如果您认为开销太大,请在 Google 上搜索“Javascript 字符串格式”,您可能会找到您喜欢的内容。
-
你可能喜欢gist.github.com/1049426,但你可以找到更多喜欢它的人。祝您搜索愉快。
标签: javascript python string formatting string-formatting