Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 13 additions & 0 deletions src/string.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -94,6 +94,19 @@ it('namedTemplate', () => {
k => String(+k * 2),
),
).toEqual('2 4 6 known key')

// Falsy values that are explicitly set should not fall back to the fallback
expect(
template('{count}', { count: 0 }, 'N/A'),
).toEqual('0')

expect(
template('{active}', { active: false }, 'unknown'),
).toEqual('false')

expect(
template('{name}', { name: '' }, 'anonymous'),
).toEqual('')
})

it('slash', () => {
Expand Down
2 changes: 1 addition & 1 deletion src/string.ts
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@ export function template(str: string, ...args: any[]): string {

if (isObject(firstArg)) {
const vars = firstArg as Record<string, any>
return str.replace(/\{(\w+)\}/g, (_, key) => vars[key] || ((typeof fallback === 'function' ? fallback(key) : fallback) ?? key))
return str.replace(/\{(\w+)\}/g, (_, key) => key in vars ? vars[key] : ((typeof fallback === 'function' ? fallback(key) : fallback) ?? key))

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Instead of in, let's use "hasOwn" to be safer?

}
else {
return str.replace(/\{(\d+)\}/g, (_, key) => {
Expand Down