braum
braum

Reputation: 29

Calculate Number Of Words based on user's input

I am trying to have a text area where the user can put text in; basically when the user clicks the button, it should calculate the number of words, the length of the shortest word, and the word; also the average length of the words, and the RMS(Root-mean-square) of the length of the words.The text area will have pre-loaded text but it should clear out the text area when user clicks on the text area so they can put whatever they want. This is what i got so far:

    $(document).ready(function () {

        $("#btnCalculate").click(function(){
            var text = $("#txtInput").val();
    text = text.replace(/\.|,|;/g, "");   //eliminate punctuation  
    //the g makes it a global replace not a replacement of the first occurrence 

    text = text.toLowerCase();           //put all text into lower case 

    text = text.replace(/\bi\b/g, "I");
    //  \b means word boundary so \bi\b means an i by iteslf which should be I 
    text = text.replace(/\s+/g, " ");  //replace white space with a simple space

    if (text.charAt(text.length - 1) == " ") {
        text = text.substring(0, text.length - 1);   // if space at end  get rid of
    }


    //longest word count
    function longestWord(str) {
        var words = str.replace(/[^A-Za-z\s]/g, "").split(" ");
        var wordsByDescendingLength = words.sort(function (a, b) {
            return b.length - a.length;
        });
        return wordsByDescendingLength[0];
    }
        });
    //shortest word
    });

Upvotes: 0

Views: 62

Answers (1)

Justin Tokarchuk
Justin Tokarchuk

Reputation: 159

String.prototype.countWords = function(){
  return this.split(/\s+/).length;
}

this should accurately do what you're looking for.

the following will strip things like punctuation:

String.prototype.countWords = function(){
  return this.split(/\s+\b/).length;
}

er, sorry on my phone. this will count number of words. I will update answer when I get to a laptop.

Upvotes: 2

Related Questions