How to interpolate variables in strings in JavaScript, without concatenation?

前端 未结 16 2233
长情又很酷
长情又很酷 2020-11-22 02:41

I know in PHP we can do something like this:

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

Output: \"I pity the foo\"<

相关标签:
16条回答
  • 2020-11-22 03:21

    Peace quote of 2020:

    Console.WriteLine("I {0} JavaScript!", ">:D<");
    
    console.log(`I ${'>:D<'} C#`)
    
    0 讨论(0)
  • 2020-11-22 03:22

    Prior to Firefox 34 / Chrome 41 / Safari 9 / Microsoft Edge, nope, that was not possible in javascript. You would have to resort to:

    var hello = "foo";
    var my_string = "I pity the " + hello;
    
    0 讨论(0)
  • 2020-11-22 03:23

    If you're trying to do interpolation for microtemplating, I like Mustache.js for that purpose.

    0 讨论(0)
  • 2020-11-22 03:25
    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"
    
    0 讨论(0)
提交回复
热议问题