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

前端 未结 16 2514
长情又很酷
长情又很酷 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:04

    Complete answer, ready to be used:

     var Strings = {
            create : (function() {
                    var regexp = /{([^{]+)}/g;
    
                    return function(str, o) {
                         return str.replace(regexp, function(ignore, key){
                               return (key = o[key]) == null ? '' : key;
                         });
                    }
            })()
    };
    

    Call as

    Strings.create("My firstname is {first}, my last name is {last}", {first:'Neo', last:'Andersson'});
    

    To attach it to String.prototype:

    String.prototype.create = function(o) {
               return Strings.create(this, o);
    }
    

    Then use as :

    "My firstname is ${first}".create({first:'Neo'});
    

提交回复
热议问题