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

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

    Create a method similar to String.format() of Java

    StringJoin=(s, r=[])=>{
      r.map((v,i)=>{
        s = s.replace('%'+(i+1),v)
      })
    return s
    }
    

    use

    console.log(StringJoin('I can %1 a %2',['create','method'])) //output: 'I can create a method'
    

提交回复
热议问题