How can I do string interpolation in JavaScript?

前端 未结 19 2527
慢半拍i
慢半拍i 2020-11-21 07:54

Consider this code:

var age = 3;

console.log(\"I\'m \" + age + \" years old!\");

Are there any other ways to insert the value of a variabl

19条回答
  •  醉酒成梦
    2020-11-21 08:11

    I use this pattern in a lot of languages when I don't know how to do it properly yet and just want to get an idea down quickly:

    // JavaScript
    let stringValue = 'Hello, my name is {name}. You {action} my {relation}.'
        .replace(/{name}/g    ,'Indigo Montoya')
        .replace(/{action}/g  ,'killed')
        .replace(/{relation}/g,'father')
        ;
    

    While not particularily efficient, I find it readable. It always works, and its always available:

    ' VBScript
    dim template = "Hello, my name is {name}. You {action} my {relation}."
    dim stringvalue = template
    stringValue = replace(stringvalue, "{name}"    ,"Luke Skywalker")     
    stringValue = replace(stringvalue, "{relation}","Father")     
    stringValue = replace(stringvalue, "{action}"  ,"are")
    

    ALWAYS

    * COBOL
    INSPECT stringvalue REPLACING FIRST '{name}'     BY 'Grendel'
    INSPECT stringvalue REPLACING FIRST '{relation}' BY 'Mother'
    INSPECT stringvalue REPLACING FIRST '{action}'   BY 'did unspeakable things to'
    

提交回复
热议问题