我知道在PHP中我们可以这样做:

$hello = "foo";
$my_string = "I pity the $hello";

输出:"I pity the foo"

我想知道同样的事情在JavaScript中是否也是可能的。在字符串中使用变量而不使用连接-它看起来更简洁和优雅。


当前回答

如果你想为微模板做插值,我喜欢用Mustache.js。

其他回答

在Firefox 34 / Chrome 41 / Safari 9 / Microsoft Edge之前,不,这在javascript中是不可能的。你将不得不求助于:

var hello = "foo";
var my_string = "I pity the " + hello;

创建一个类似于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'

也许

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

如果你想为微模板做插值,我喜欢用Mustache.js。

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"