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

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

    Don't see any external libraries mentioned here, but Lodash has _.template(),

    https://lodash.com/docs/4.17.10#template

    If you're already making use of the library it's worth checking out, and if you're not making use of Lodash you can always cherry pick methods from npm npm install lodash.template so you can cut down overhead.

    Simplest form -

    var compiled = _.template('hello <%= user %>!');
    compiled({ 'user': 'fred' });
    // => 'hello fred!'
    

    There are a bunch of configuration options also -

    _.templateSettings.interpolate = /{{([\s\S]+?)}}/g;
    var compiled = _.template('hello {{ user }}!');
    compiled({ 'user': 'mustache' });
    // => 'hello mustache!'
    

    I found custom delimiters most interesting.

提交回复
热议问题