Counting occurrences of a word in a string Javascript [closed]

北城余情 提交于 2019-12-02 22:52:38

问题


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,


回答1:


var counts = myString.replace/[^\w\s]/g, "").split(/\s+/).reduce(function(map, word){
    map[word] = (map[word]||0)+1;
    return map;
}, Object.create(null));



回答2:


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)



来源:https://stackoverflow.com/questions/14914046/counting-occurrences-of-a-word-in-a-string-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!