代码之家  ›  专栏  ›  技术社区  ›  Muhammad Umer

可以用变量列表做字符串插值吗?

  •  0
  • Muhammad Umer  · 技术社区  · 6 年前

    我知道你能做到:

    let a = 'building';
    console.log(`it's a tall ${a}`);
    

    但是像这样的事情呢:

    let b = 'building';
    let text = 'it's a tall $x`;
    console.log(text.interpolate({x: b}));
    
    1 回复  |  直到 6 年前
        1
  •  1
  •   CertainPerformance    6 年前

    为传递的对象中的每个键构造一个全局正则表达式,并将其替换为其关联的值:

    function escapeRegExp(string) {           // https://stackoverflow.com/questions/3561493/is-there-a-regexp-escape-function-in-javascript
      return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
    }
    
    let a = 'foo';
    let b = 'building';
    let text = "$y $y it's a tall $x $y";
    
    const interpolate = (input, obj) => Object.entries(obj).reduce((a, [key, replaceStr]) => (
      a.replace(new RegExp(escapeRegExp('$' + key), 'g'), replaceStr)
    ), input);
    console.log(interpolate(text, {x: b, y: a}));