Applied Programming/Strings/JavaScript

strings.js

edit
/* This program counts words in entered strings.

Input:
    Text string

Output:
    Word count

Example:
    Enter a string or press <Enter> to quit:
     The cat in the hat.
    You entered 5 words.

    Enter a string or press <Enter> to quit:
    ...

References:
    None
 */

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

/**
  * Runs the main program logic.
  */
function main() {
    try {
        while (true) {
            let text = getText();
            if (text == "") {
                break;
            }

            let wordCount = countWords(text);
            displayResults(wordCount);
        }
    }
    catch (error) {
        console.log("Unexpected error:");
        console.log(`${error.name}: ${error.message}`);
    }
}

/**
 * Gets text string.
 * 
 * @return  Text string entered.
 */
function getText() {
    let text = prompt("Enter a string or press <Enter> to quit: ");
    return text;
}

/**
 * Counts words in text.
 * 
 * @param   text
 * @return  count of words in text
 */
function countWords(text) {
    const SEPARATORS = " ~`!@#$%^&*()-_=+{}[]|\\:;\"'<>,.?/";
    let wordCount = 0;
    let inWord = false;
    for (let i = 0; i < text.length; i++) {
        if (!inWord && !SEPARATORS.includes(text.substring(i, i + 1))) {
            wordCount += 1;
            inWord = true;
        }
        else if (inWord && SEPARATORS.includes(text.substring(i, i + 1))) {
            inWord = false;
        }
    }
    return wordCount;
}

/**
 * Displays the word count.
 * 
 * @param {number} word count
 */
function displayResults(wordCount) {
    console.log(`You entered ${wordCount} word(s).`);
}

/**
 * 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