VOOZH about

URL: https://en.wikiversity.org/wiki/Applied_Programming/Strings/JavaScript

⇱ Applied Programming/Strings/JavaScript - Wikiversity


Jump to content
From Wikiversity

strings.js

[edit | edit source]
/* 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(typeofmodule!="undefined"&&!module.parent){
main();
}

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

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

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

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

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

/**
 * Input function to get input in Node environment.
 * 
 * @param {string} text prompt
 * @returns {string} input
 */
functionprompt(text){
constrls=require('readline-sync');
letvalue=rls.question(text);
returnvalue;
}

Try It

[edit | edit source]

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 | edit source]