Joe
Joe

Reputation: 107

Count word occurrence in the json file returned from wikipedia api

I am trying to count the occurrence of a word in the json file returned from wikipedia api.

For example, I want to count the occurrence of apple in the json file.

https://en.wikipedia.org/w/api.php?action=parse&section=0&prop=text&format=json&page=apple

I have got some code, but it didn't work.

var wikiURL =  "https://en.wikipedia.org/w/api.php?action=parse&section=0&prop=text&format=json&page=apple"

$.ajax({
    // ajax settings
    url: wikiURL,
    method: "GET",
    dataType: "jsonp",    
}).done(function (data) {
    // successful
    var temp =data.parse.text;
    console.log(temp);
    // temp is an object, how to count word apple from it?

}).fail(function () {
    // error handling
    alert("failed");
});

Upvotes: 0

Views: 279

Answers (1)

Igor Ilic
Igor Ilic

Reputation: 1368

You could do it like this:

var wikiURL =  "https://en.wikipedia.org/w/api.php?action=parse&section=0&prop=text&format=json&page=apple"

$.ajax({
    // ajax settings
    url: wikiURL,
    method: "GET",
    dataType: "jsonp",    
}).done(function (data) {
    // successful
    var temp = data.parse.text['*'];

    const regex = /(apple)+/gmi; //g - globally, m - multi line, i - case insensitive 
    let m;
    let cnt = 0;
    while ((m = regex.exec(temp)) !== null) {
        // This is necessary to avoid infinite loops with zero-width matches
        if (m.index === regex.lastIndex) {
            regex.lastIndex++;
        }
        cnt++;
        // The result can be accessed through the `m`-variable.
        /*m.forEach((match, groupIndex) => {
            console.log(`Found match, group ${groupIndex}: ${match}`);
        });*/
    }
    console.log(cnt); //
}).fail(function () {
    // error handling
    alert("failed");
});

You can see regex in action here: https://regex101.com/r/v9Uoh6/1

Upvotes: 2

Related Questions