Intl.ListFormat.prototype.formatToParts()

Baseline Widely available

This feature is well established and works across many devices and browser versions. It’s been available across browsers since April 2021.

Die formatToParts()-Methode von Intl.ListFormat-Instanzen gibt ein Array von Objekten zurück, das jedes Teil des formatierten Strings repräsentiert, der von format() zurückgegeben würde. Sie ist nützlich, um benutzerdefinierte Strings aus den lokalspezifischen Token zu erstellen.

Probieren Sie es aus

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"]"

Syntax

js
formatToParts(list)

Parameter

list

Ein iterierbares Objekt, wie ein Array, das Strings enthält. Wenn es weggelassen wird, wird das leere Array formatiert, was leicht verwirrend sein kann. Daher ist es ratsam, immer explizit eine Liste zu übergeben.

Rückgabewert

Ein Array von Objekten, das die formatierte Liste in Teilen enthält. Jedes Objekt hat zwei Eigenschaften, type und value, die jeweils einen String enthalten. Die stringmäßige Verkettung von value in der angegebenen Reihenfolge ergibt denselben String wie format(). Der type kann einer der folgenden sein:

literal

Jeder String, der Teil des Formatmusters ist, zum Beispiel ", ", ", and" usw.

element

Ein Element der Liste, genau so wie es übergeben wurde.

Beispiele

Verwenden von 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" }
// ]

Spezifikationen

Specification
ECMAScript® 2026 Internationalization API Specification
# sec-Intl.ListFormat.prototype.formatToParts

Browser-Kompatibilität

Siehe auch