我知道在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中是否也是可能的。在字符串中使用变量而不使用连接-它看起来更简洁和优雅。
当前回答
Var hello = "foo";
var my_string ="I pity the";
console.log (my_string,你好)
其他回答
这里没有看到任何外部库,但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!'
我发现自定义分隔符非常有趣。
在Firefox 34 / Chrome 41 / Safari 9 / Microsoft Edge之前,不,这在javascript中是不可能的。你将不得不求助于:
var hello = "foo";
var my_string = "I pity the " + hello;
你可以这么做,但它不是一般的
'I pity the $fool'.replace('$fool', 'fool')
如果确实需要,您可以轻松地编写一个函数来智能地执行此操作
Var hello = "foo";
var my_string ="I pity the";
console.log (my_string,你好)
创建一个类似于Java的String.format()的方法
StringJoin=(s, r=[])=>{
r.map((v,i)=>{
s = s.replace('%'+(i+1),v)
})
return s
}
use
console.log(StringJoin('I can %1 a %2',['create','method'])) //output: 'I can create a method'