如何在 JavaScript 中插入字符串中的变量而不使用连接?
我知道在 PHP 中我们可以做这样的事情:
$hello = "foo";
$my_string = "I pity the $hello";
Output: "I pity the foo"
我想知道在 JavaScript 中是否也可以做同样的事情。在字符串中使用变量而不使用连接——看起来写起来更加简洁和优雅。
I know in PHP we can do something like this:
$hello = "foo";
$my_string = "I pity the $hello";
Output: "I pity the foo"
I was wondering if this same thing is possible in JavaScript as well. Using variables inside strings without using concatenation — it looks more concise and elegant to write.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(18)
您可以利用模板文字并使用此语法:
该功能已在 ES2015(ES6)中引入。
示例
这有多简洁?
奖励:
它还允许在 javascript 中使用多行字符串而无需转义,这对于模板来说非常有用:
浏览器支持:
由于旧版浏览器(主要是 Internet Explorer)不支持此语法,您可能需要使用 Babel/Webpack 将您的代码转换为 ES5,以确保它可以在任何地方运行。
旁注:
从 IE8+ 开始,您可以在
console.log
中使用基本字符串格式:You can take advantage of Template Literals and use this syntax:
This feature has been introduced in ES2015 (ES6).
Example
How neat is that?
Bonus:
It also allows for multi-line strings in javascript without escaping, which is great for templates:
Browser support:
As this syntax is not supported by older browsers (mostly Internet Explorer), you may want to use Babel/Webpack to transpile your code into ES5 to ensure it will run everywhere.
Side note:
Starting from IE8+ you can use basic string formatting inside
console.log
:之前的 Firefox 34 / Chrome 41 / Safari 9 / Microsoft Edge,不,这在 javascript 中是不可能的。您将不得不求助于:
Prior to Firefox 34 / Chrome 41 / Safari 9 / Microsoft Edge, nope, that was not possible in javascript. You would have to resort to:
Firefox 34 / Chrome 41 / Safari 9 / Microsoft Edge 之前,没有。尽管您可以尝试 sprintf for JavaScript 来达到目的:
Prior to Firefox 34 / Chrome 41 / Safari 9 / Microsoft Edge, no. Although you could try sprintf for JavaScript to get halfway there:
好吧,你可以做到这一点,但这不是特别普遍的,
如果你真的需要的话,你可以轻松地编写一个智能地执行此操作的函数
well you could do this, but it's not esp general
You could easily write a function that does this intelligently if you really needed to
如果缺少 ES6,则完成并准备使用答案:
调用 as
将其附加到
String.prototype
:然后使用 as :
如果您使用 >ES6< /strong> 那么你也可以这样做:
Complete and ready to be used answer if lacking ES6:
Call as
To attach it to
String.prototype
:Then use as :
If you are on >ES6 then you can also do:
2022 更新:只需使用 ES6 模板文字功能。 几乎所有您现在遇到的浏览器都完全支持它。如果您仍然以 IE11 及更低版本等浏览器为目标……那么,我很同情您。我 5 年前提出的以下解决方案仍然适用于您。另外,如果您想要一份不涉及旧浏览器的工作,请给我发电子邮件。
您可以使用此 javascript 函数来执行此类模板化。无需包含整个库。
输出:
“我想从这家商店接收电子邮件更新 FOO BAR BAZ。”
使用函数作为 String.replace() 函数的参数是ECMAScript v3 规范。有关更多信息,请参阅这个答案细节。
2022 update: Just use the ES6 Template Literals feature. It's fully supported in practically every browser you'll encounter these days. If you are still targeting browsers like IE11 and lower .. well, my heart goes out to you. The below solution I came up with 5 years ago will still work for you. Also, email me if you want a job that doesn't involve catering to old browsers ????.
You can use this javascript function to do this sort of templating. No need to include an entire library.
Output:
"I would like to receive email updates from this store FOO BAR BAZ."
Using a function as an argument to the String.replace() function was part of the ECMAScript v3 spec. See this SO answer for more details.
如果您喜欢编写 CoffeeScript,您可以这样做:
CoffeeScript 实际上是 javascript,但具有更好的语法。
有关 CoffeeScript 的概述,请查看此初学者指南。
If you like to write CoffeeScript you could do:
CoffeeScript actually IS javascript, but with a much better syntax.
For an overview of CoffeeScript check this beginner's guide.
我会使用反引号``。
但如果您在创建
msg1
时不知道name1
。例如,如果
msg1
来自 API。您可以使用:
它将用他的值替换
${name2}
。I would use the back-tick ``.
But if you don't know
name1
when you createmsg1
.For exemple if
msg1
came from an API.You can use :
It will replace
${name2}
with his value.我写了这个 npm 包 stringinject https://www.npmjs.com/package/stringinject 它允许您可以执行以下操作
,将 {0} 和 {1} 替换为数组项并返回以下字符串
,或者您可以将占位符替换为对象键和值,如下所示:
I wrote this npm package stringinject https://www.npmjs.com/package/stringinject which allows you to do the following
which will replace the {0} and {1} with the array items and return the following string
or you could replace placeholders with object keys and values like so:
如果您尝试对微模板进行插值,我喜欢 Mustache.js 来实现此目的。
If you're trying to do interpolation for microtemplating, I like Mustache.js for that purpose.
没有看到这里提到的任何外部库,但 Lodash 有
_.template()
,https://lodash.com/docs/4.17.10#template
如果您已经在使用该库,那么值得一试,如果您没有使用 Lodash,您可以始终从 npm
npm install lodash.template
中挑选方法,这样您就可以减少开销。最简单的形式 -
还有很多配置选项 -
我发现自定义分隔符最有趣。
Don't see any external libraries mentioned here, but Lodash has
_.template()
,https://lodash.com/docs/4.17.10#template
If you're already making use of the library it's worth checking out, and if you're not making use of Lodash you can always cherry pick methods from npm
npm install lodash.template
so you can cut down overhead.Simplest form -
There are a bunch of configuration options also -
I found custom delimiters most interesting.
只需使用:
Simply use:
的
String.format()
的方法创建类似于Java使用
Create a method similar to
String.format()
of Javause
2020年和平报价:
Peace quote of 2020:
或许
Maybe
输出=>
您好用户
注意
使用 `` 不要使用 "" 或 '' 它不会起作用
output =>
<a href=''><i class='fa-solid fa-star'></i>Hello User</a>
note
use `` don't use "" or '' it will not work
乌索:
Uso:
var hello = "foo";
console.log(my_string, 你好)
var hello = "foo";
console.log(my_string, hello)