简体   繁体   English

用双引号包装javascript变量

[英]wrapping a javascript variable with double quotes

I've the following code with a string inside a js template literal. 我在js模板文字中使用了一个字符串以下代码。

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

I want to wrap the ${value} with double quotes when it prints. 我打算在打印时用双引号包装${value} How can I achieve this? 我怎样才能做到这一点?

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

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

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

Just use the double quote surrounding your ${value} 只需使用${value}周围的双引号

UPDATES: 更新:

Just to try out to prove that it can supports double quoted string as below 只是为了证明它可以支持双引号字符串,如下所示

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

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

Using JSON.stringify will do the right thing for all JS primitives, quoting strings, and correctly formatting objects and arrays. 使用JSON.stringify将为所有JS基元做正确的事情,引用字符串,并正确格式化对象和数组。

EDIT because so many of other answerers seem to be missing the point: 编辑,因为许多其他的回答者似乎忽略了这一点:

 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"; 

Just wrapping ${value} inside double quotes does not seem to be a problem: 只是将${value}包装在双引号内似乎不是问题:

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

Here is a snippet.... 这是一个片段....

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM