@mudssky/jsutils
    Preparing search index...

    Function parseTemplate

    • 解析模板字符串,并将占位符替换为数据对象中的值。

      Parameters

      • str: string

        包含占位符的模板字符串。

      • data: Record<string, any>

        一个记录,其键是占位符的名称(不带括号),值是替换内容。

      • regex: RegExp = ...

        用于匹配占位符的正则表达式。默认为 /{{(.+?)}}/g,匹配 {{placeholder}} 格式。

      Returns string

      替换占位符后的字符串。

      const template = "Hello {{name}}, welcome to {{place}}!";
      const data = { name: "World", place: "our app" };
      console.log(parseTemplate(template, data));
      // -> "Hello World, welcome to our app!"

      const customTemplate = "Hi <user>, your id is <id>.";
      const customData = { user: "Alex", id: "123" };
      const customRegex = /<(.+?)>/g;
      console.log(parseTemplate(customTemplate, customData, customRegex));
      // -> "Hi Alex, your id is 123."