我知道在PHP中我们可以这样做:
$hello = "foo";
$my_string = "I pity the $hello";
输出:"I pity the foo"
我想知道同样的事情在JavaScript中是否也是可能的。在字符串中使用变量而不使用连接-它看起来更简洁和优雅。
我知道在PHP中我们可以这样做:
$hello = "foo";
$my_string = "I pity the $hello";
输出:"I pity the foo"
我想知道同样的事情在JavaScript中是否也是可能的。在字符串中使用变量而不使用连接-它看起来更简洁和优雅。
当前回答
2020年和平语录:
Console.WriteLine("I {0} JavaScript!", ">:D<");
console.log(`I ${'>:D<'} C#`)
其他回答
我写了这个npm包stringinject https://www.npmjs.com/package/stringinject,它允许你做以下事情
var string = stringInject("this is a {0} string for {1}", ["test", "stringInject"]);
这将替换{0}和{1}与数组项,并返回以下字符串
"this is a test string for stringInject"
或者你可以像这样用对象键和值替换占位符:
var str = stringInject("My username is {username} on {platform}", { username: "tjcafferkey", platform: "GitHub" });
"My username is tjcafferkey on Github"
String.prototype.interpole = function () {
var c=0, txt=this;
while (txt.search(/{var}/g) > 0){
txt = txt.replace(/{var}/, arguments[c]);
c++;
}
return txt;
}
Uso:
var hello = "foo";
var my_string = "I pity the {var}".interpole(hello);
//resultado "I pity the foo"
完整且随时可用的回答<ES6:
var Strings = {
create : (function() {
var regexp = /{([^{]+)}/g;
return function(str, o) {
return str.replace(regexp, function(ignore, key){
return (key = o[key]) == null ? '' : key;
});
}
})()
};
电话是
Strings.create("My firstname is {first}, my last name is {last}", {first:'Neo', last:'Andersson'});
将它附加到String.prototype:
String.prototype.create = function(o) {
return Strings.create(this, o);
}
然后使用as:
"My firstname is ${first}".create({first:'Neo'});
如果你在>ES6上,那么你也可以这样做:
let first = 'Neo';
`My firstname is ${first}`;
这里没有看到任何外部库,但Lodash有_.template(),
https://lodash.com/docs/4.17.10#template
如果你已经在使用Lodash库,它值得一试,如果你没有使用Lodash,你可以从npm npm install Lodash中选择方法。模板,这样可以减少开销。
最简单的形式——
var compiled = _.template('hello <%= user %>!');
compiled({ 'user': 'fred' });
// => 'hello fred!'
还有很多配置选项
_.templateSettings.interpolate = /{{([\s\S]+?)}}/g;
var compiled = _.template('hello {{ user }}!');
compiled({ 'user': 'mustache' });
// => 'hello mustache!'
我发现自定义分隔符非常有趣。
你可以利用模板字面量并使用以下语法:
`String text ${expression}`
模板字面量由后撇号(' ')(严肃重音)括起来,而不是双引号或单引号。
该特性已在ES2015 (ES6)中引入。
例子
var a = 5;
var b = 10;
console.log(`Fifteen is ${a + b}.`);
// "Fifteen is 15.
多简洁啊?
奖金:
它还允许在javascript中使用多行字符串而无需转义,这对于模板来说非常棒:
return `
<div class="${foo}">
...
</div>
`;
浏览器支持:
由于旧的浏览器(主要是Internet Explorer)不支持这种语法,您可能希望使用Babel/Webpack将代码转译到ES5中,以确保它可以在任何地方运行。
注:
从IE8+开始,你可以在console.log中使用基本的字符串格式:
console.log('%s is %d.', 'Fifteen', 15);
// Fifteen is 15.