user3466687
user3466687

Reputation: 249

google javascript spreadsheet

I am trying to make function that tells me how many there are words that contains less than 3 letters. For example, "Tomorrow will be rain. So bring your umbrellas" in this sentence, only "be" and "so" so equal two. Any help would be appreciated.

function (stri){

return ("less than 3 ").length;

}

( I am aiming to use \w (regular expression) if its possible.)

Upvotes: 0

Views: 71

Answers (2)

Chad Hedgcock
Chad Hedgcock

Reputation: 11785

function countSmallWords(stringToTest){
  var smallWords = /\b\w{1,2}\b/g;
  return stringToTest.match(smallWords).length;
}

Explanation: It uses the regular expression \b\w{1,2}\b with the global flag to match all words in a string that are one or two characters. Then it uses the match function on that string to give an array of the words. Finally, get the length property for the count.

Example usage:

//Example 1:
alert(countSmallWords("Tomorrow will be rain. So bring your umbrellas"));
//alerts 2

//Example 2:
var smallWordCount = countSmallWords("Hello. What a nice day it is.");
//smallWordCount == 3

//Example 3:
var smallWordCount = countSmallWords("Are there any small words in this sentence?");
console.log(smallWordCount);
//Press F12 and you will see 1 in the browser console.

Upvotes: 1

Shanimal
Shanimal

Reputation: 11718

If you use lodash you can do the following...

<script src="http://cdnjs.cloudflare.com/ajax/libs/lodash.js/2.4.1/lodash.min.js"></script>
<script>

    // create a function to call with your string and the min size of the word
    function countSmalls(s,min) {

      // split by non word characters
      return _.where(s.split(/\W/),function(v,i,l){

        // return true or false to satisfy the callback, all *truthy* values are added to the return value of _.where
        return v && v.length < min;
      }).length;
    }

    // create some text
    var lorem = "Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.";

    // call your function
    countSmalls(lorem,3); // 24 (words that are < 3 characters)

</script>

Upvotes: 1

Related Questions