JavaScript equivalent of Python#39;s format() function?(JavaScript 等效于 Python 的 format() 函数?)
问题描述
Python 有一个漂亮的函数来转这个:
Python has this beautiful function to turn this:
bar1 = 'foobar'
bar2 = 'jumped'
bar3 = 'dog'
foo = 'The lazy ' + bar3 + ' ' + bar2 ' over the ' + bar1
# The lazy dog jumped over the foobar
进入这个:
bar1 = 'foobar'
bar2 = 'jumped'
bar3 = 'dog'
foo = 'The lazy {} {} over the {}'.format(bar3, bar2, bar1)
# The lazy dog jumped over the foobar
JavaScript有这样的功能吗?如果不是,我将如何创建一个遵循与 Python 实现相同的语法?
Does JavaScript have such a function? If not, how would I create one which follows the same syntax as Python's implementation?
推荐答案
另一种方法,使用 String.prototype.replace
方法,第二个参数是replacer"函数:
Another approach, using the String.prototype.replace
method, with a "replacer" function as second argument:
String.prototype.format = function () {
var i = 0, args = arguments;
return this.replace(/{}/g, function () {
return typeof args[i] != 'undefined' ? args[i++] : '';
});
};
var bar1 = 'foobar',
bar2 = 'jumped',
bar3 = 'dog';
'The lazy {} {} over the {}'.format(bar3, bar2, bar1);
// "The lazy dog jumped over the foobar"
这篇关于JavaScript 等效于 Python 的 format() 函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:JavaScript 等效于 Python 的 format() 函数?


基础教程推荐
- Chart.js 在线性图表上拖动点 2022-01-01
- 我可以在浏览器中与Babel一起使用ES模块,而不捆绑我的代码吗? 2022-01-01
- Electron 将 Node.js 和 Chromium 上下文结合起来意味着 2022-01-01
- Vue 3 – <过渡>渲染不能动画的非元素根节点 2022-01-01
- html表格如何通过更改悬停边框来突出显示列? 2022-01-01
- 直接将值设置为滑块 2022-01-01
- 如何使用JIT在顺风css中使用布局变体? 2022-01-01
- 用于 Twitter 小部件宽度的 HTML/CSS 2022-01-01
- 如何使用TypeScrip将固定承诺数组中的项设置为可选 2022-01-01
- 自定义 XMLHttpRequest.prototype.open 2022-01-01