MCPcopy Create free account
hub / github.com/antfu/utils / template

Function template

src/string.ts:65–80  ·  view source on GitHub ↗
(str: string, ...args: any[])

Source from the content-addressed store, hash-verified

63export function template(str: string, object: Record<string | number, any>, fallback?: string | ((key: string) => string)): string
64export function template(str: string, ...args: (string | number | bigint | undefined | null)[]): string
65export function template(str: string, ...args: any[]): string {
66 const [firstArg, fallback] = args
67
68 if (isObject(firstArg)) {
69 const vars = firstArg as Record<string, any>
70 return str.replace(/\{(\w+)\}/g, (_, key) => vars[key] || ((typeof fallback === 'function' ? fallback(key) : fallback) ?? key))
71 }
72 else {
73 return str.replace(/\{(\d+)\}/g, (_, key) => {
74 const index = Number(key)
75 if (Number.isNaN(index))
76 return key
77 return args[index]
78 })
79 }
80}
81
82// port from nanoid
83// https://github.com/ai/nanoid

Callers 1

string.test.tsFile · 0.90

Calls 1

isObjectFunction · 0.90

Tested by

no test coverage detected