Patrick Conboy
Patrick Conboy

Reputation: 709

Word counter in javascript

I'm working on a lab assignment for a web applications class and am stuck on implementing a word counter for a basic HTML webpage. The setup of the tests and HTML are already done for us. I simply need to write a function called countWords that takes a string and returns the number of words. It works differently from your traditional word counter though. A word is defined as anything A-Z. Everything else is considered not part of a word. So, if the string is just "234@#$^" then the word count is 0. So, I'm not just counting white space like most word counters. All the answers I've found on StackOverflow to similar questions try to just count white space and don't work for my situation. Hence why I made a new question.

My idea was to have a return statement that matches any grouping of a-z using a regular expression and return the length. Then, have a conditional to check for the empty string or string with no letters a-z.

function countWords(s) {
   if(s === "" || s === "%$#^23#") {
      return 0
   }
   return s.match(/[^a-z]/gi).length
}

Right now the if statement is just matching the two test cases so that I can pass my tests. I'm not sure how to go about writing another match regular expression to check for no letters in the string or the empty string. Any help is appreciated! Been stuck for a while.

Upvotes: 1

Views: 495

Answers (4)

noirsociety
noirsociety

Reputation: 374

const str1 = '%$#^23#';
const str2 = 'String with  ___ special characters and @$&# white spaces  !!!';
const str3 = 'Special &$%# characters --> and %$#^5# connected,words but our <++@@||++> function,still_works!';

const wordCount = (str) => str.replace(/[\W_\d]/g,' ').split(' ').filter(Boolean).length;

console.log(wordCount(str1)); // 0
console.log(wordCount(str2)); // 7
console.log(wordCount(str3)); // 11
  1. use "regex" to replace all special characters, underscores, numbers, and extra white spaces with an empty space

    --> replace(/[\W_\d]/g,' ')

  2. convert the string into an array

    --> .split(' ')

  3. use filter to remove all empty string(s) in the array

    --> .filter(Boolean)

  4. then, get the word count with "length"

    --> .length

Upvotes: 1

TheWandererLee
TheWandererLee

Reputation: 1032

How about this regular expression: /.*?[a-z]+.*?(\s|$)/gi

Use return s.match(/.*?[a-z]+.*?(\s|$)/gi).length

Anything with at least 1 letter in it is counted. Then the phrase O##ne two $#!+ @#%Three four^&&$ five would count as 5 words.

Edit: If you want to be evil to pass your test cases when there are 0 matches use (input.match(/.*?[a-z]+.*?(\s|$)/gi) || "").length

Upvotes: 0

zfrisch
zfrisch

Reputation: 8660

You can use a functional replace method to chunk all of the "words" into an array, then simply return the array length. This has the added benefit of providing a 0 count:


explanatory version:

function countWords(str, words = []) {
  str.replace(/[A-Z]+/gi, (m) => words.push(m));
  return words.length;
}

minimal version:

let countWords = (str, words = []) => 
    ( str.replace(/[A-Z]+/gi, (m) => words.push(m)), words.length );

let countWords = (str, words = []) => (str.replace(/[A-Z]+/gi, (m) => words.push(m)), words.length);

console.log( "##asdfadf###asfadf: " + countWords("##asdfadf###asfadf") )
console.log("##13424#$#$#$%: " + countWords("##13424#$#$#$%"));

Upvotes: 0

Ramy M. Mousa
Ramy M. Mousa

Reputation: 5933

You first need to filter the string, remove all the special characters and numbers:

var filtered_test = my_text.replace(/[^a-zA-Z ]/g, '');

then do a normal split and count:

var words = filtered_test.split(" ");
console.log(words.length); //prints out the count of words

Upvotes: 0

Related Questions