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

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

    I wrote this npm package stringinject https://www.npmjs.com/package/stringinject which allows you to do the following

    var string = stringInject("this is a {0} string for {1}", ["test", "stringInject"]);
    

    which will replace the {0} and {1} with the array items and return the following string

    "this is a test string for stringInject"
    

    or you could replace placeholders with object keys and values like so:

    var str = stringInject("My username is {username} on {platform}", { username: "tjcafferkey", platform: "GitHub" });
    
    "My username is tjcafferkey on Github" 
    

提交回复
热议问题