Applied Programming/RegEx/JavaScript

regex.js

edit
/* This program demonstrates regex and dictionary processing.

Input:
    None

Output:
    The cat in the hat.
    { the: 2, cat: 1, in: 1, hat: 1 }
    cat: 1
    hat: 1
    in: 1
    the: 2

References:
    https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/matchAll
    https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in
*/

if (typeof module != "undefined" && !module.parent) {
    main();
}

/**
 * Runs main program logic.
 */
function main() {
    const text = "The cat in the hat.";
    console.log(text);

    let wordCount = getWordCount(text);
    console.log(wordCount);
    displayWordCount(wordCount);
}

/**
 * Processes text and returns word counts.
 * 
 * @param {string} text words to process
 * @returns {object} words and count
 */
function getWordCount(text) {
    const pattern = /\w+/g
    const matches = text.matchAll(pattern);
    let wordCount = {};
    for(const match of matches) {
        const word = match[0].toLowerCase();
        if (word in wordCount == false) {
            wordCount[word] = 0;
        }
        wordCount[word] += 1;
    }
    return wordCount;
}

/**
 * Displays word counts.
 * 
 * @param {object} words and count
 */
function displayWordCount(wordCount) {
    const words = Object.keys(wordCount).sort();

    for (const word of words) {
        console.log(`${word}: ${wordCount[word]}`);
    }
}

/**
 * Input function to get input in Node environment.
 * 
 * @param {string} text prompt
 * @returns {string} input
 */
function prompt(text) {
    const rls = require('readline-sync');
    let value = rls.question(text);
    return value;
}

Try It

edit

Copy and paste the code above into one of the following free online development environments or use your own JavaScript compiler / interpreter / IDE.

See Also

edit