I know in PHP we can do something like this:
我知道在PHP中我们可以这样做:
$hello = "foo";
$my_string = "I pity the $hello";
Output: "I pity the foo"
输出:“我同情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是否也有同样的功能。在字符串中使用变量而不使用连接——它看起来更简洁和优雅。
10 个解决方案
#1
311
Starting from Firefox 34 / Chrome 41 / Safari 9 / Microsoft Edge you can use an ES2015 / ES6 feature called Template Literals and use this syntax:
从Firefox 34 / Chrome 41 / Safari 9 / Microsoft Edge开始,您可以使用名为Template Literals的ES2015 / ES6特性,并使用以下语法:
`String text ${expression}`
Template literals are enclosed by the back-tick (` `) (grave accent) instead of double or single quotes.
模板文字由后勾(')(严重的重音)而不是双引号或单引号括起来。
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 (Internet Explorer and Safari <= 8), you may want to use Babel to transpile your code into ES5 to ensure it will run everywhere.
由于旧的浏览器不支持这种语法(Internet Explorer和Safari <= 8),您可能希望使用Babel将您的代码转换为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.
#2
149
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之前,这在javascript中是不可能的。你不得不求助于:
var hello = "foo";
var my_string = "I pity the " + hello;
#3
37
Prior to Firefox 34 / Chrome 41 / Safari 9 / Microsoft Edge, no. Although you could try sprintf for JavaScript to get halfway there:
火狐34 / Chrome 41 / Safari 9 /微软Edge之前,没有。尽管您可以尝试使用sprintf来实现JavaScript:
var hello = "foo";
var my_string = sprintf("I pity the %s", hello);
#4
20
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
如果你真的需要这样做,你可以很容易地写出一个函数。
#5
7
If you like to write CoffeeScript you could do:
如果你喜欢写咖啡,你可以这样做:
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.
要了解咖啡稿的概述,请阅读本初学者指南。
#6
6
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.create = function(o) {
return Strings.create(this, o);
}
Then use as :
然后使用:
"My firstname is ${first}".create({first:'Neo'});
#7
6
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."
输出:“我想收到这个商店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.
使用函数作为字符串的参数。replace()函数是ECMAScript v3规范的一部分。
#8
4
If you're trying to do interpolation for microtemplating, I like Mustache.js for that purpose.
如果你想做微模板插值,我喜欢小胡子。js。
#9
2
I wrote this npm package stringinject https://www.npmjs.com/package/stringinject which 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"
#10
0
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模板
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.
如果您已经在使用这个库,那么它是值得检查的,如果您没有使用Lodash,您可以从npm npm安装Lodash中选择方法。模板,这样可以减少开销。
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.
我发现自定义分隔符最有趣。
#1
311
Starting from Firefox 34 / Chrome 41 / Safari 9 / Microsoft Edge you can use an ES2015 / ES6 feature called Template Literals and use this syntax:
从Firefox 34 / Chrome 41 / Safari 9 / Microsoft Edge开始,您可以使用名为Template Literals的ES2015 / ES6特性,并使用以下语法:
`String text ${expression}`
Template literals are enclosed by the back-tick (` `) (grave accent) instead of double or single quotes.
模板文字由后勾(')(严重的重音)而不是双引号或单引号括起来。
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 (Internet Explorer and Safari <= 8), you may want to use Babel to transpile your code into ES5 to ensure it will run everywhere.
由于旧的浏览器不支持这种语法(Internet Explorer和Safari <= 8),您可能希望使用Babel将您的代码转换为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.
#2
149
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之前,这在javascript中是不可能的。你不得不求助于:
var hello = "foo";
var my_string = "I pity the " + hello;
#3
37
Prior to Firefox 34 / Chrome 41 / Safari 9 / Microsoft Edge, no. Although you could try sprintf for JavaScript to get halfway there:
火狐34 / Chrome 41 / Safari 9 /微软Edge之前,没有。尽管您可以尝试使用sprintf来实现JavaScript:
var hello = "foo";
var my_string = sprintf("I pity the %s", hello);
#4
20
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
如果你真的需要这样做,你可以很容易地写出一个函数。
#5
7
If you like to write CoffeeScript you could do:
如果你喜欢写咖啡,你可以这样做:
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.
要了解咖啡稿的概述,请阅读本初学者指南。
#6
6
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.create = function(o) {
return Strings.create(this, o);
}
Then use as :
然后使用:
"My firstname is ${first}".create({first:'Neo'});
#7
6
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."
输出:“我想收到这个商店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.
使用函数作为字符串的参数。replace()函数是ECMAScript v3规范的一部分。
#8
4
If you're trying to do interpolation for microtemplating, I like Mustache.js for that purpose.
如果你想做微模板插值,我喜欢小胡子。js。
#9
2
I wrote this npm package stringinject https://www.npmjs.com/package/stringinject which 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"
#10
0
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模板
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.
如果您已经在使用这个库,那么它是值得检查的,如果您没有使用Lodash,您可以从npm npm安装Lodash中选择方法。模板,这样可以减少开销。
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.
我发现自定义分隔符最有趣。