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, die jeweils einen Teil des formatierten Strings darstellen, der von format()
zurückgegeben würde. Sie ist nützlich, um benutzerspezifische 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
formatToParts(list)
Parameter
list
-
Ein iterierbares Objekt, wie zum Beispiel ein Array, das Strings enthält. Wird es weggelassen, führt dies zur Formatierung eines leeren Arrays, was leicht verwirrend sein kann. Es wird daher empfohlen, 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 Verkettung der Strings in value
in der angegebenen Reihenfolge ergibt denselben String wie format()
. Der type
kann einer der folgenden sein:
Beispiele
Nutzung 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® 2025 Internationalization API Specification # sec-Intl.ListFormat.prototype.formatToParts |
Browser-Kompatibilität
Report problems with this compatibility data on GitHubdesktop | mobile | server | ||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
formatToParts |
Legend
Tip: you can click/tap on a cell for more information.
- Full support
- Full support
- See implementation notes.