JSFiddle - React, Tailwind, and code Playground

by Alexander Shutov

JavaScript

var input = 'this is a,\nsample of\na file.';

// Find words
var matches = input.match(/\b[A-Za-z]+\b/g);

// Calculate count
var words = [];
matches.forEach(function (m) {
    var found = words.filter(function (w) {
        return w.word === m;
    });
    if (found.length > 0) {
        found[0].count++;
    } else {
        words.push({
            word: m,
            count: 1
        });
    }
});

// Sort
words.sort(function (a, b) {
    return a.count > b.count ? -1 : a.count < b.count ? 1 : 0;
});

// Output
alert(words.map(function (w) {
    return w.word + ': ' + w.count;
}).join('\n'));