Skip to content

interpolateList

字符串插值(占位符替换)

参数

参数名参数类型参数说明
messagestring模版字符串
valuesunknown[] | Record<string, unknown>替换的值集合

源代码&使用

ts
import { interpolateList } from "@botaoxy/utilsxy";

let info = "Hello, {0} {1}.";
interpolateList(info, ["I'm", "Botao"])

let info1 = "Hello, {value} {name}.";
interpolateList(info, value: "I'm", name: "Botao")

// Hello, I'm Botao.
ts
/*
 * @Author: Chengbotao
 * @Contact: https://github.com/chengbotao
 */
import { isEmpty } from '../isxxx';

export function interpolateList(
  message: string,
  values: unknown[] | Record<string, unknown>
): string {
  if (isEmpty(values)) {
    return message;
  }
  if (Array.isArray(values)) {
    return message.replace(/\{(\d+)\}/g, (match, index) => {
      const value = values[index] as string;
      return value !== undefined ? value : match;
    });
  }
  return message.replace(/\{([^}]+)\}/g, (match, key) => {
    const value = values[key] as string;
    return value !== undefined ? value : match;
  });
}