Course contentsShow
← JavaScript
Lesson 2226 of 2,72346. InternationalizationFree lesson

The formatToParts() Method

Breaking down relative time strings into parts for custom rendering and styling.

The formatToParts() Method

You'll learn how to break apart relative time strings into individual pieces for full styling control.

Beyond Simple Strings

Until now, format() gave you complete relative time strings like "in 3 days" or "2 weeks ago". But what if you need to style the number differently from the text, or rearrange parts for a custom UI? That's where formatToParts() shines.

Instead of returning a single string, formatToParts() returns an array of objects, each representing one piece of the formatted output. Every object has a type (like "integer" or "literal") and a value (the actual text).

Breaking Down the Parts

const rtf = new Intl.RelativeTimeFormat('en', { numeric: 'auto' });

const parts = rtf.formatToParts(-2, 'day');
console.log(parts);
// [
//   { type: 'integer', value: '2' },
//   { type: 'literal', value: ' days ago' }
// ]

const parts2 = rtf.formatToParts(3, 'hour');
console.log(parts2);
// [
//   { type: 'literal', value: 'in ' },
//   { type: 'integer', value: '3' },
//   { type: 'literal', value: ' hours' }
// ]

Custom Rendering

With parts separated, you can style each individually:

const parts = rtf.formatToParts(5, 'minute');

const styledHTML = parts
  .map(part => {
    if (part.type === 'integer') {
      return `<strong>${part.value}</strong>`;
    }
    return part.value;
  })
  .join('');

console.log(styledHTML); // "in <strong>5</strong> minutes"

You can also filter, reorder, or translate specific parts without parsing the entire string manually.

Key Takeaway: formatToParts() gives you granular access to each component of a relative time string, enabling custom styling, layout, and rendering that simple format() cannot provide.