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

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

输出:"I pity the foo"

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


当前回答

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

其他回答

我会使用反撇号' '。

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}。

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

Var hello = "foo";

var my_string ="I pity the";

console.log (my_string,你好)

你可以这么做,但它不是一般的

'I pity the $fool'.replace('$fool', 'fool')

如果确实需要,您可以轻松地编写一个函数来智能地执行此操作

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