如何在不连接的情况下在 JavaScript 中的字符串中插入变量?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3304014/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to interpolate variables in strings in JavaScript, without concatenation?
提问by DMin
I know in PHP we can do something like this:
我知道在 PHP 中我们可以做这样的事情:
$hello = "foo";
$my_string = "I pity the $hello";
Output: "I pity the foo"
输出: "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.
我想知道在 JavaScript 中是否也可以实现同样的事情。在字符串中使用变量而不使用连接? - 写起来更简洁优雅。
回答by bformet
You can take advantage of Template Literalsand use this syntax:
您可以利用模板文字并使用以下语法:
`String text ${expression}`
Template literals are enclosed by the back-tick (` `)(grave accent) instead of double or single quotes.
模板文字由反引号(` `)(重音符号)而不是双引号或单引号括起来。
This feature has been introduced in ES2015 (ES6).
这个特性已经在 ES2015 (ES6) 中引入。
Example
例子
var a = 5;
var b = 10;
console.log(`Fifteen is ${a + b}.`);
// "Fifteen is 15.
How neat is that?
那有多整洁?
Bonus:
奖金:
It also allows for multi-line strings in javascript without escaping, which is great for templates:
它还允许在 javascript 中使用多行字符串而无需转义,这对模板非常有用:
return `
<div class="${foo}">
...
</div>
`;
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.
由于较旧的浏览器(主要是 Internet Explorer)不支持此语法,您可能需要使用Babel/Webpack 将您的代码转换为 ES5,以确保它可以在任何地方运行。
Side note:
边注:
Starting from IE8+ you can use basic string formatting inside console.log:
从 IE8+ 开始,您可以在内部使用基本的字符串格式console.log:
console.log('%s is %d.', 'Fifteen', 15);
// Fifteen is 15.
回答by Sarfraz
回答by Justin Ethier
Prior toFirefox 34 / Chrome 41 / Safari 9 / Microsoft Edge, no. Although you could try sprintf for JavaScriptto get halfway there:
在Firefox 34 / Chrome 41 / Safari 9 / Microsoft Edge 之前,没有。尽管您可以尝试使用sprintf for JavaScript来实现一半:
var hello = "foo";
var my_string = sprintf("I pity the %s", hello);
回答by Scott Evernden
well you could do this, but it's not esp general
好吧,你可以这样做,但这不是一般的
'I pity the $fool'.replace('$fool', 'fool')
You could easily write a function that does this intelligently if you really needed to
如果您真的需要,您可以轻松编写一个智能地执行此操作的函数
回答by mmm
Complete answer, ready to be used:
完整的答案,准备使用:
var Strings = {
create : (function() {
var regexp = /{([^{]+)}/g;
return function(str, o) {
return str.replace(regexp, function(ignore, key){
return (key = o[key]) == null ? '' : key;
});
}
})()
};
Call as
调用为
Strings.create("My firstname is {first}, my last name is {last}", {first:'Neo', last:'Andersson'});
To attach it to String.prototype:
将它附加到 String.prototype:
String.prototype.create = function(o) {
return Strings.create(this, o);
}
Then use as :
然后用作:
"My firstname is ${first}".create({first:'Neo'});
回答by Eric Seastrand
You can use this javascript function to do this sort of templating. No need to include an entire library.
你可以使用这个 javascript 函数来做这种模板。无需包含整个库。
function createStringFromTemplate(template, variables) {
return template.replace(new RegExp("\{([^\{]+)\}", "g"), function(_unused, varName){
return variables[varName];
});
}
createStringFromTemplate(
"I would like to receive email updates from {list_name} {var1} {var2} {var3}.",
{
list_name : "this store",
var1 : "FOO",
var2 : "BAR",
var3 : "BAZ"
}
);
Output: "I would like to receive email updates from this store FOO BAR BAZ."
输出:"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 answerfor more details.
使用函数作为 String.replace() 函数的参数是 ECMAScript v3 规范的一部分。有关更多详细信息,请参阅此 SO 答案。
回答by bformet
If you like to write CoffeeScript you could do:
如果您喜欢编写 CoffeeScript,您可以这样做:
hello = "foo"
my_string = "I pity the #{hello}"
CoffeeScript actually IS javascript, but with a much better syntax.
CoffeeScript 实际上是 javascript,但具有更好的语法。
For an overview of CoffeeScript check this beginner's guide.
有关 CoffeeScript 的概述,请查看此初学者指南。
回答by Joe Martinez
If you're trying to do interpolation for microtemplating, I like Mustache.jsfor that purpose.
如果您正在尝试为微模板进行插值,我喜欢Mustache.js用于此目的。
回答by tjcafferkey
I wrote this npm package stringinject https://www.npmjs.com/package/stringinjectwhich allows you to do the following
我写了这个 npm 包 stringinject https://www.npmjs.com/package/stringinject它允许您执行以下操作
var string = stringInject("this is a {0} string for {1}", ["test", "stringInject"]);
which will replace the {0} and {1} with the array items and return the following string
这将用数组项替换 {0} 和 {1} 并返回以下字符串
"this is a test string for stringInject"
or you could replace placeholders with object keys and values like so:
或者您可以用对象键和值替换占位符,如下所示:
var str = stringInject("My username is {username} on {platform}", { username: "tjcafferkey", platform: "GitHub" });
"My username is tjcafferkey on Github"
回答by Mark Carpenter Jr
Don't see any external libraries mentioned here, but Lodash has _.template(),
没有看到这里提到的任何外部库,但 Lodash 有_.template(),
https://lodash.com/docs/4.17.10#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.templateso you can cut down overhead.
如果您已经在使用该库,那么值得一试,如果您没有使用 Lodash,您总是可以从 npm 中挑选方法,npm install lodash.template这样您就可以减少开销。
Simplest form -
最简单的形式——
var compiled = _.template('hello <%= user %>!');
compiled({ 'user': 'fred' });
// => 'hello fred!'
There are a bunch of configuration options also -
还有一堆配置选项 -
_.templateSettings.interpolate = /{{([\s\S]+?)}}/g;
var compiled = _.template('hello {{ user }}!');
compiled({ 'user': 'mustache' });
// => 'hello mustache!'
I found custom delimiters most interesting.
我发现自定义分隔符最有趣。

