Wikipedia article summary / leading paragraph extraction / GET in plain text

Wikipedia article summary / leading paragraph extraction / GET, in plain text using JSOP.

by gautamadude

HTML

<p>An approch to getting the summary / leading paragraph out of Wikipedia
    articlies within the browser using JSONP with the Wikipedia API.</p>
<br>

<h2>Insert into textarea</h2>

<textarea id="foo"></textarea>
<br>

<h2>Insert into div</h2>

<div id="plain_text"></div>

CSS

h2 {
    font-weight: bold;
}
textarea {
    width: 100%;
    height: 300px;
}

JavaScript

//Getting leading paragraphs from Wikipedia articles, using the Wikipedia API: http://en.wikipedia.org/w/api.php

var page = "http://en.wikipedia.org/wiki/Gautama_Buddha";
var title = page.split("/");
title = title[title.length - 1];

//Leading paragraphs
$.getJSON("http://en.wikipedia.org/w/api.php?action=parse&page=" + title + "&prop=text&section=0&format=json&callback=?", function (data) {
    var text = data["parse"]["text"]["*"].split("<p>");
    var pText = "";
    
    for (p in text) {
        //Remove html comment
        text[p] = text[p].split("<!--");
        if (text[p].length > 1) {
            text[p][0] = text[p][0].split(/\r\n|\r|\n/);
            text[p][0] = text[p][0][0];
            text[p][0] += "</p> ";
        }
        text[p] = text[p][0];
        
        //Construct a string from paragraphs
        if (text[p].indexOf("</p>") == text[p].length-5) {
            var htmlStrip = text[p].replace(/<(?:.|\n)*?>/gm, '') //Remove HTML
            var splitNewline = htmlStrip.split(/\r\n|\r|\n/); //Split on newlines
            for (newline in splitNewline) {
              if (splitNewline[newline].substring(0, 11) != "Cite error:") {
                    pText += splitNewline[newline];
                    pText += "\n";
                }   
            }
        }
    }
    pText = pText.substring(0, pText.length - 2); //Remove extra newline
    //Insert into page
    $("#foo").val(pText);
    $("#plain_text").html(pText);
});