用双引号包装 JavaScript 变量



我有以下代码,在 js 模板文字中有一个字符串。

`${currentType} ${objProp} = ${value};`

我想在打印时用双引号包装${value}。我怎样才能做到这一点?

let currentType = "hello";
let objProp = "world";
let value = "hi";
let a = `${currentType} ${objProp} = "${value}";`
console.log(a)

只需使用双引号将${value}

更新:

只是为了尝试证明它可以支持双引号字符串,如下所示

let value = '"hi"';
let a = `${value}`;
console.log(a)
let value2 = ""hi"";
let a2 = `${value2}`;
console.log(a2)

`${currentType} ${objProp} = ${JSON.stringify(value)};`

使用JSON.stringify将对所有 JS 原语做正确的事情,引用字符串并正确格式化对象和数组。

编辑,因为许多其他回答者似乎没有抓住重点:

let currentType = 'string';
let objProp = 'actor';
let value = 'Dwayne "The Rock" Johnson';
let bad = `${currentType} ${objProp} = "${value}";`
console.log(bad);
// string actor = "Dwayne "The Rock" Johnson";
let good = `${currentType} ${objProp} = ${JSON.stringify(value)};`
console.log(good);
// string actor = "Dwayne "The Rock" Johnson";

因为使用的是 ES6 字符串模板,所以可以在模板中使用双引号 ("( 或单引号 ('(。因此,这应该有效:

`${currentType} ${objProp} = "${value};"`

只是将${value}括在双引号内似乎不是问题:

var currentType = 11;
var objProp = "test";
var value = 33;
var templateVar = `${currentType} ${objProp} = "${value}";`
console.log(templateVar);

这是一个片段....

let val = "1243"
let k = `"${val}"`
console.log(k)

最新更新