@adventera/vectara-ui
Version:
Vectara's design system, codified as a React component library
25 lines (24 loc) • 880 B
JavaScript
export const extractCitations = (summary) => {
// Match citations.
// const regex = /\[(\d+)\]/g;
const regex = /\[(\d+(,*\s*\d*)*)\]/g;
const citations = [];
let match;
let lastIndex = 0;
// Parse all cited content.
while ((match = regex.exec(summary)) !== null) {
const index = match.index;
const reference = match[1];
const text = summary.slice(lastIndex, index).trim();
// Handle citations that are in the form of [1, 2, 3] or [1,2,3]
// so normalize to the latter.
citations.push({ text, references: reference.replace(/\s/g, "").split(",") });
lastIndex = index + match[0].length;
}
// Add the remaining content after the last citation.
const text = summary.slice(lastIndex).trim();
if (text.length > 0) {
citations.push({ text });
}
return citations;
};