interpolateList
字符串插值(占位符替换)
参数
参数名 | 参数类型 | 参数说明 |
---|---|---|
message | string | 模版字符串 |
values | unknown[] | 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;
});
}