JavaScript 中的字符串插值?
考虑这段代码:
var age = 3;
console.log("I'm " + age + " years old!");
除了字符串连接之外,还有其他方法可以将变量的值插入到字符串中吗?
Consider this code:
var age = 3;
console.log("I'm " + age + " years old!");
Are there any other ways to insert the value of a variable in to a string, apart from string concatenation?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(18)
如果您想在
console.log
输出中进行插值,那么这里的
%s
就是所谓的“格式说明符”。console.log
内置了这种插值支持。If you want to interpolate in
console.log
output, then justHere,
%s
is what is called a "format specifier".console.log
has this sort of interpolation support built-in.您可以轻松地使用 ES6
模板字符串
并使用任何可用的转译器(如 babel)转译为 ES5。http://www.es6fiddle.net/im3c3euc/
You can do easily using ES6
template string
and transpile to ES5 using any available transpilar like babel.http://www.es6fiddle.net/im3c3euc/
您可以使用反引号``和ES6模板字符串
You can use the backticks `` and ES6 template string
这是一个需要您提供带有值的对象的解决方案。如果您不提供对象作为参数,它将默认使用全局变量。但最好坚持使用参数,这样会干净得多。
Here's a solution which requires you to provide an object with the values. If you don't provide an object as parameter, it will default to using global variables. But better stick to using the parameter, it's much cleaner.
尝试 kiwi,一个轻量级 JavaScript 模块用于字符串插值。
你可以做
或者
Try kiwi, a light-weight JavaScript module for string interpolation.
You can do
or
找不到我要找的东西,然后找到了它 -
如果您使用 Node.js,有一个内置的
util
包,其中包含一个格式函数,其工作原理如下:巧合的是,这就是现在Node.js 中也内置了
console.log
风格 -Couldn't find what I was looking for, then found it -
If you're using Node.js, there's a built-in
util
package with a format function that works like this:Coincidentally this is now built into
console.log
flavors too in Node.js -扩展Greg Kindel的第二个答案,您可以编写一个函数来消除一些样板文件:
用法:
Expanding on Greg Kindel's second answer, you can write a function to eliminate some of the boilerplate:
Usage:
从 ES6 开始,如果你想在对象键中进行字符串插值,如果你执行以下操作,你将得到一个
SyntaxError: Expected property name, got '${'
:你应该执行以下操作:
Since ES6, if you want to do string interpolation in object keys, you will get a
SyntaxError: expected property name, got '${'
if you do something like:You should do the following instead:
虽然模板可能最适合您描述的情况,但如果您拥有或想要可迭代/数组形式的数据和/或参数,则可以使用
String.raw
。将数据作为数组,可以使用扩展运算符:
While templates are probably best for the case you describe, if you have or want your data and/or arguments in iterable/array form, you can use
String.raw
.With the data as an array, one can use the spread operator:
自定义灵活插值:
Custom flexible interpolation:
从 ES6 开始,您可以使用模板文字:
PS 注意反引号的使用:
``
。Since ES6, you can use template literals:
P.S. Note the use of backticks:
``
.tl;dr
使用 ECMAScript 2015 的模板字符串文字(如果适用)。
说明
根据 ECMAScript 5 规范,没有直接的方法可以做到这一点,但 ECMAScript 6 有 模板字符串,在起草过程中也被称为准文字规格像这样使用它们:
您可以在
{}
内使用任何有效的 JavaScript 表达式。例如:另一个重要的事情是,您不必再担心多行字符串。您可以将它们简单地写为
注意: 我使用 io.js v2.4.0 来评估上面显示的所有模板字符串。您还可以使用最新的 Chrome 来测试上面显示的示例。
注意: ES6 规范现已最终确定,但是尚未被所有主流浏览器实现。
根据 Mozilla 开发者网络页面,这将是从以下版本开始实现基本支持:Firefox 34、Chrome 41、Internet Explorer 12。如果您是 Opera、Safari 或 Internet Explorer 用户并且现在对此感到好奇,此测试床可用于试用,直到每个人都得到支持。
tl;dr
Use ECMAScript 2015's Template String Literals, if applicable.
Explanation
There is no direct way to do it, as per ECMAScript 5 specifications, but ECMAScript 6 has template strings, which were also known as quasi-literals during the drafting of the spec. Use them like this:
You can use any valid JavaScript expression inside the
{}
. For example:The other important thing is, you don't have to worry about multi-line strings anymore. You can write them simply as
Note: I used io.js v2.4.0 to evaluate all the template strings shown above. You can also use the latest Chrome to test the above shown examples.
Note: ES6 Specifications are now finalized, but have yet to be implemented by all major browsers.
According to the Mozilla Developer Network pages, this will be implemented for basic support starting in the following versions: Firefox 34, Chrome 41, Internet Explorer 12. If you're an Opera, Safari, or Internet Explorer user and are curious about this now, this test bed can be used to play around until everyone gets support for this.
Douglas Crockford 的 Remedial JavaScript 包含一个
String.prototype.supplant
函数。它简短、熟悉且易于使用:如果您不想更改 String 的原型,您可以随时将其调整为独立的,或将其放入其他名称空间或其他名称中。
Douglas Crockford's Remedial JavaScript includes a
String.prototype.supplant
function. It is short, familiar, and easy to use:If you don't want to change String's prototype, you can always adapt it to be standalone, or place it into some other namespace, or whatever.
警告:避免任何不允许您转义其自身分隔符的模板系统。例如,使用此处提到的
supplant()
方法将无法输出以下内容。简单的插值可能适用于小型独立脚本,但通常会带来这种设计缺陷,从而限制任何严肃的使用。老实说,我更喜欢 DOM 模板,例如:
并使用 jQuery 操作:
$('#age').text(3)
或者,如果您只是厌倦了字符串连接,总是有替代语法:
Word of caution: avoid any template system which does't allow you to escape its own delimiters. For example, There would be no way to output the following using the
supplant()
method mentioned here.Simple interpolation may work for small self-contained scripts, but often comes with this design flaw that will limit any serious use. I honestly prefer DOM templates, such as:
And use jQuery manipulation:
$('#age').text(3)
Alternately, if you are simply just tired of string concatenation, there's always alternate syntax:
当我还不知道如何正确执行并且只想快速记下一个想法时,我在很多语言中使用这种模式:
虽然不是特别有效,但我发现它具有可读性。它始终有效,并且始终可用:
始终
更新:
我原以为这是不言而喻的,但事实证明事实并非如此。只要有要循环的键/值对,您就可以应用此功能。
我最近一直在 pl/SQL 中使用这个。
I use this pattern in a lot of languages when I don't know how to do it properly yet and just want to get an idea down quickly:
While not particularily efficient, I find it readable. It always works, and its always available:
ALWAYS
UPDATE:
I had thought it was self-evident, but it was made clear to me that it was not. You can apply this anytime you have a key/value pair to loop through.
I've been using this in pl/SQL lately.
如果你真的想用大锤来破解坚果,你可以使用 Prototype 的模板系统 :
You could use Prototype's template system if you really feel like using a sledgehammer to crack a nut:
尝试 sprintf 库(一个完整的开源 JavaScript sprintf 实现)。例如:
vsprintf 接受一个参数数组并返回一个格式化字符串。
Try sprintf library (a complete open source JavaScript sprintf implementation). For example:
vsprintf takes an array of arguments and returns a formatted string.
最简单的是
一种效率较低的方法来实现这一点,可以
与
The simplest would be
a less efficient way to accomplish this would be
which can be used with