我知道在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#`)
其他回答
2020年和平语录:
Console.WriteLine("I {0} JavaScript!", ">:D<");
console.log(`I ${'>:D<'} C#`)
简单的使用方法:
var util = require('util');
var value = 15;
var s = util.format("The variable value is: %s", value)
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"
也许
wrt=(s, arr=[])=>{
arr.map((v,i)=>{s = s.replace(/\?/,v);});
return s;
};
a='first var';
b='secondvar';
tr=wrt('<tr><td>?<td></td>?</td><tr>',[a,b]);
console.log(tr);
//or use tr in html(tr), append(tr) so on and so forth
// Use ? with care in s
我会使用反撇号' '。
let name1 = 'Geoffrey';
let msg1 = `Hello ${name1}`;
console.log(msg1); // 'Hello Geoffrey'
但如果在创建msg1时不知道name1。
例如,如果msg1来自API。
你可以使用:
let name2 = 'Geoffrey';
let msg2 = 'Hello ${name2}';
console.log(msg2); // 'Hello ${name2}'
const regexp = /\${([^{]+)}/g;
let result = msg2.replace(regexp, function(ignore, key){
return eval(key);
});
console.log(result); // 'Hello Geoffrey'
它将用他的值替换${name2}。