Public
Edited
Oct 4, 2023
1 star
Insert cell
Insert cell
wtf=require('wtf_wikipedia')
Insert cell
doc = await wtf.fetch('Anarchism')
Insert cell
page_doc = doc.json()
Insert cell
test_sentence = page_doc.sections[0].paragraphs[0].sentences[0]
Insert cell

function applyLinksToText(sentence) {
let { text, links } = sentence;

// Filter out entries without a 'text' field
links = links.filter(link => link.text);

// Sort links by the text length in descending order to handle overlapping words
links.sort((a, b) => b.text.length - a.text.length);

links.forEach(link => {
const { text: linkText, page } = link;
const slug = page.charAt(0).toUpperCase() + page.slice(1).replace(/\s+/g, '_');
const linkSyntax = `[[${linkText} | ${slug}]]`;

// Using a global RegExp to replace all occurrences of linkText
const regex = new RegExp(`\\b${linkText}\\b`, 'g');
text = text.replace(regex, linkSyntax);
});

return text;
}

Insert cell
applyLinksToText(test_sentence)
Insert cell
doc.json().sections[2]
Insert cell

Purpose-built for displays of data

Observable is your go-to platform for exploring data and creating expressive data visualizations. Use reactive JavaScript notebooks for prototyping and a collaborative canvas for visual data exploration and dashboard creation.
Learn more