我知道在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#`)
其他回答
Var hello = "foo";
var my_string ="I pity the";
console.log (my_string,你好)
在Firefox 34 / Chrome 41 / Safari 9 / Microsoft Edge之前,不,这在javascript中是不可能的。你将不得不求助于:
var hello = "foo";
var my_string = "I pity the " + hello;
完整且随时可用的回答<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}`;
你可以这么做,但它不是一般的
'I pity the $fool'.replace('$fool', 'fool')
如果确实需要,您可以轻松地编写一个函数来智能地执行此操作
如果你喜欢写CoffeeScript,你可以这样做:
hello = "foo"
my_string = "I pity the #{hello}"
CoffeeScript实际上是javascript,但是语法更好。
要了解CoffeeScript的概述,请查看初学者指南。