1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
| function formatString(str: string, ...args: unknown[]): string {
return str.replace(/\{(\d+)\}/g, (match, indexText) => {
const index = Number(indexText);
return typeof args[index] !== 'undefined'
? String(args[index])
: match;
});
}
const name = 'Alice';
const age = 25;
const message = formatString(
'My name is {0} and I am {1} years old.',
name,
age
);
console.log(message);
// My name is Alice and I am 25 years old.
|
The regular expression captures the numeric index inside each placeholder. The callback uses that index to retrieve the corresponding argument. If the argument is missing, the original placeholder remains unchanged.