TypeScript写一个类似于`format.string`方法

代码:

1
2
3
4
5
6
7
8
9
10
function formatString(str: string, ...args: any[]): string {
return str.replace(/\{(\d+)\}/g, (match, index) => {
return typeof args[index] !== "undefined" ? args[index] : match;
});
}

const name: string = "Alice";
const age: number = 25;
const message: string = formatString("My name is {0} and I am {1} years old.", name, age);
console.log(message); // Output: "My name is Alice and I am 25 years old."

在上面的示例中,我们定义了一个名为 formatString 的函数,它接受一个字符串和任意数量的参数。在函数体内,我们使用正则表达式 /\\{\\d+\\}/g 来匹配字符串中的占位符 {},并在每个匹配项上调用一个回调函数来进行替换。

在回调函数中,我们使用 args 数组来获取与占位符 {} 中的索引对应的参数。如果参数存在,则将其用于替换占位符。否则,我们返回匹配项本身。最后,我们返回替换后的字符串。

在示例中,我们还定义了两个变量 nameage,并使用 formatString 函数来将它们的值嵌入到字符串中。最后,我们输出格式化后的字符串 message,它的值是 "My name is Alice and I am 25 years old."