This particular element is designed to handle the task at hand. It shares similarities with the above answer, but I have personally crafted this version! The assumption here is that the bold segments are always in sorted order. Keep in mind that it does not perform any argument validation, so use caution!
function FormattedLine({ text, boldSubstrings }) {
let position = 0;
const fragments = [];
boldSubstrings.forEach(({ offset, length }) => {
if (position < offset) {
const paragraph = text.substr(position, offset - position);
fragments.push({ text: paragraph, isBold: false });
}
if (length) {
fragments.push({ text: text.substr(offset, length), isBold: true });
position = offset + length;
}
});
if (position < text.length) {
fragments.push({
text: text.substr(position, text.length - position),
isBold: false
});
}
return (
<p>
{fragments.map(({ text: fragmentText, isBold }) =>
isBold ? <b>{fragmentText}</b> : fragmentText
)}
</p>
);
}