Jump to content

User:Polygnotus/Scripts/WikiPageToArray.js

From Wikipedia, the free encyclopedia
Note: After saving, you have to bypass your browser's cache to see the changes. Google Chrome, Firefox, Microsoft Edge and Safari: Hold down the ⇧ Shift key and click the Reload toolbar button. For details and instructions about other browsers, see Wikipedia:Bypass your cache.
async function fetchWikitextArray(pageName) {
  const apiUrl = `https://en.wikipedia.org/w/api.php?action=parse&page=${encodeURIComponent(pageName)}&prop=wikitext&format=json&origin=*`;

  try {
    const response = await fetch(apiUrl);
    const data = await response.json();
    
    if (data.parse && data.parse.wikitext) {
      const wikitext = data.parse.wikitext['*'];
      return wikitext
        .split('\n')
        .map(line => line.trim())
        .filter(line => line !== '');
    } else {
      throw new Error('Failed to retrieve wikitext');
    }
  } catch (error) {
    console.error('Error fetching wikitext:', error);
    return [];
  }
}


async function example() {
  try {
    const pageName = 'User:Polygnotus/Scripts/WikiPageToArrayTest';
    const wikitextArray = await fetchWikitextArray(pageName);
    console.log(`Wikitext array for "${pageName}" page:`);
    console.log(wikitextArray);
    console.log(`Number of lines: ${wikitextArray.length}`);
  } catch (error) {
    console.error('Error in example:', error);
  }
}

example();