Python有一个漂亮的函数来实现这一点:
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实现相同语法的?
另一种方法,使用^{} 方法,使用“replacer”函数作为第二个参数:
tl;博士
为什么仅仅模板字符串是不够的
ES6template strings提供了一个与pythons字符串格式非常相似的特性。但是,在构造字符串之前,必须知道变量:
为什么格式化?
Python的
str.format
允许您在之前指定字符串您甚至知道要插入到其中的值,例如:解决方案
使用arrow function,我们可以优雅地包装模板字符串以供以后使用:
当然,这也适用于正则函数,但是arrow函数允许我们将其设为一行。这两种功能在大多数浏览器和运行时中都可用:
有一种方法,但不是完全使用格式。
jsfiddle-link
相关问题 更多 >
编程相关推荐