2024年5月30日发(作者:)

js 的format函数

在 JavaScript 中,没有内置的 format 函数。但你可以使用一些第三

方库或自定义函数来实现格式化功能。以下是一个简单的示例,演示

如何使用自定义函数实现字符串的格式化:

javascript

function format(template, ...values) {

return e(/{(d+)}/g, (match, number) => {

return typeof values[number] !== 'undefined' ? values[number] :

match;

});

}

const name = "John";

const age = 30;

const formattedString = format("My name is {0} and I'm {1} years

old.", name, age);

(formattedString); // 输出:My name is John and I'm 30

years old.

在上面的示例中,format 函数接受一个模板字符串和一系列值,然后

将模板字符串中的 {0}、{1} 等占位符替换为相应的值。你可以根据需

要传递任意数量的值,并使用它们来格式化字符串。

请注意,这只是一个简单的示例,可能无法满足所有格式化需求。如

果你需要更复杂的格式化功能,可以考虑使用一些流行的 JavaScript

库,如 或 te。