-1

Does anyone know a simple way of counting the occurrences of a word in a Javascript String, without a predefined list of words that will be available? Ideally I would like it to output into an associative array (Word, Count).

For example an input along the lines of "Hello how are you Hello" would output something along the lines of:- "Hello": 2 "how": 1 "are": 1 "you": 1

Any help is greatly appreciated.

Thanks,

user1840255
  • 287
  • 1
  • 6
  • 15

2 Answers2

4

For a simple string this should suffice:

var str = "hello hello hello this is a list of different words that it is",
    split = str.split(" "),
    obj = {};

for (var x = 0; x < split.length; x++) {
  if (obj[split[x]] === undefined) {
    obj[split[x]] = 1;
  } else {
    obj[split[x]]++;
  }
}

console.log(obj)

If you want to process sentences though, you'll need to do some handling of punctuation etc (so, replace all the !?.'s with spaces)

adiga
  • 34,372
  • 9
  • 61
  • 83
Doug
  • 3,312
  • 1
  • 24
  • 31
  • Thank you, that's brilliant. As someone else had suggested this wasn't for homework but a project I'm working on. Thanks again. – user1840255 Feb 16 '13 at 19:19
  • You should not check for values to be undefined, but test for `split[x] in obj` – Bergi Feb 16 '13 at 19:22
4
var counts = myString.replace/[^\w\s]/g, "").split(/\s+/).reduce(function(map, word){
    map[word] = (map[word]||0)+1;
    return map;
}, Object.create(null));
Bergi
  • 630,263
  • 148
  • 957
  • 1,375