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 Methode formatToParts()
von Intl.ListFormat
-Instanzen gibt ein Array von Objekten zurück, das jeweils einen Teil des formatierten Strings darstellt, der von format()
zurückgegeben würde. Dies ist nützlich, um benutzerdefinierte Strings aus den lokal spezifischen 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
formatToParts(list)
Parameter
list
-
Ein iterierbares Objekt, wie z.B. ein Array, das Strings enthält. Wird es weggelassen, wird das leere Array formatiert, was etwas verwirrend sein könnte, daher ist es ratsam, immer ausdrücklich 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 String-Verkettung von value
in der angegebenen Reihenfolge resultiert in dem gleichen String wie bei format()
. Der type
kann einer der folgenden sein:
Beispiele
Verwendung von formatToParts()
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 |