For AI agents: the complete documentation index is available at /tc39-atlas/llms.txt, the full documentation bundle is available at /tc39-atlas/llms-full.txt, and this page is available as Markdown at /tc39-atlas/proposals/intl-numberformat-prototype-formattoparts.md.
  • 简体中文
  • Intl.NumberFormat.prototype.formatToParts S4

    提案概览
    提案速览

    该提案为 Intl.DateTimeFormat 和 Intl.NumberFormat 添加了 formatToParts 方法,允许对格式化输出的各个部分进行本地化处理,以实现自定义样式或操作。提案解决了访问格式化输出(如月份、货币)的个别组成部分以实现高级显示的需求。它包含了参考实现和测试。

    Note

    以下 README 来自上游仓库,其中的阶段或状态标注可能滞后;当前信息以提案概览为准。

    DateTimeFormat.prototype.formatToParts / NumberFormat.prototype.formatToParts

    提案,规范,测试和参考实现,用于 DateTimeFormat.prototype.formatToParts 和 NumberFormat.prototype.formatToParts。

    状态

    第 4 阶段

    实现进展

    • Polyfill
    • Gecko 补丁

    反向指针

    作者

    • Caridy Patiño (@caridy)
    • Eric Ferraiuolo (@ericf)
    • Zibi Braniecki (@zbraniecki)

    审阅者

    待定

    信息性

    此提案支持对 Intl 格式化器产生的字符串进行区域设置感知的格式化。

    用法

    
    let dateFormatter = Intl.DateTimeFormat('en', {
      year: 'numeric',
      month: 'long',
      day: 'numeric'
    });
    let now = new Date();
    
    let dateStr = dateFormatter.formatToParts(now).map(({type, value}) => {
      switch (type) {
        case 'month': return `<b>${value}</b>`;
        default     : return value;
      }
    }).reduce((string, part) => string + part);
    
    console.log(dateFormatter.format(now)); // yields "November 23, 2015"
    console.log(dateStr); // yields "<b>November</b> 23, 2015"
    
    
    let numFormatter = Intl.NumberFormat('en', {
      style: 'currency',
      currency: 'EUR',
    });
    let amount = -1000;
    
    let numStr = numFormatter.formatToParts(amount).map(({type, value}) => {
      switch (type) {
        case 'currency': return `<b>${value}</b>`;
        case 'number'  : return `<i>${value}</i>`;
        default        : return value;
      }
    }).reduce((string, part) => string + part);
    
    console.log(numFormatter.format(amount)); // yields "-€1,000.00"
    console.log(numStr); // yields "-<b>€</b><i>1,000.00</i>"