By using our mini forum, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy

Q: Count Words in a Text - JavaScript task

+3 votes

You are tasked to count the number of words in a text using an object as an associative array, any combination of letters, digits and _ (underscore) should be counted as a word. The words should be stored in the object as properties - the key being the word and the value being the amount of times the word is contained in the text.

The input comes as an array of strings containing one entry - the text whose words should be counted. The text may consist of more than one sentence.


Far too slow, you're far too slow.


JS devs use Node.js for server-side JS.-- JS for devs


The output should be printed on the console - the JSON representation of the object containing the words.

asked in JavaScript category by user hues

1 Answer

+2 votes

Here is the javascript code:

function countWords(input) {
    let text = input.join("\n");
    let words = text.split(/[^A-Za-z0-9_]+/)//^ in the beginning is NOT here
        .filter(w=>w != "");

    let wordCounts = {};
    for (let w of words) {
        wordCounts[w] ? wordCounts[w]++:
            wordCounts[w] = 1;


//    "Far too slow, you're far too slow."

    "JS devs use Node.js for server-side JS.-- JS for devs"


answered by user icabe