Intl.ListFormat.prototype.formatToParts()

Baseline 已广泛支持

此特性已得到良好支持,可在多种设备和浏览器版本上使用。自 2021 年 4 月起,所有浏览器均已支持此特性。

formatToParts() 方法的 Intl.ListFormat 实例返回一个对象数组,这些对象表示由 format() 返回的格式化字符串的每个部分。这对于根据本地化特定的令牌构建自定义字符串很有用。

试一试

const vehicles = ["Motorcycle", "Bus", "Car"];

const formatterEn = new Intl.ListFormat("en", {
  style: "long",
  type: "conjunction",
});

const formatterFr = new Intl.ListFormat("fr", {
  style: "long",
  type: "conjunction",
});

const partValuesEn = formatterEn.formatToParts(vehicles).map((p) => p.value);
const partValuesFr = formatterFr.formatToParts(vehicles).map((p) => p.value);

console.log(partValuesEn);
// Expected output: "["Motorcycle", ", ", "Bus", ", and ", "Car"]"
console.log(partValuesFr);
// Expected output: "["Motorcycle", ", ", "Bus", " et ", "Car"]"

语法

js
formatToParts(list)

参数

list

一个可迭代对象,例如 Array,包含字符串。省略它将格式化空数组,这可能会造成一些困惑,因此建议始终显式传递列表。

返回值

一个对象 Array,包含格式化列表的各个部分。每个对象有两个属性:typevalue,它们都包含一个字符串。按提供顺序连接 value 字符串将得到与 format() 相同的字符串。type 可以是以下之一:

literal

格式化模式的任何字符串部分;例如 ", "", and" 等。

element

列表中的一个元素,与其提供的完全一致。

示例

使用 formatToParts()

js
const fruits = ["Apple", "Orange", "Pineapple"];
const myListFormat = new Intl.ListFormat("en-GB", {
  style: "long",
  type: "conjunction",
});

console.table(myListFormat.formatToParts(fruits));
// [
//  { "type": "element", "value": "Apple" },
//  { "type": "literal", "value": ", " },
//  { "type": "element", "value": "Orange" },
//  { "type": "literal", "value": " and " },
//  { "type": "element", "value": "Pineapple" }
// ]

规范

规范
ECMAScript® 2026 国际化 API 规范
# sec-Intl.ListFormat.prototype.formatToParts

浏览器兼容性

另见