计算字符串Javascript中单词的出现次数 [英] Counting occurrences of a word in a string Javascript

查看:87
本文介绍了计算字符串Javascript中单词的出现次数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有人知道一种简单的方法来计数Javascript字符串中某个单词的出现,而没有一个可用的预定义单词列表?理想情况下,我希望它输出到一个关联数组(Word,Count)。

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).

例如,输入 Hello,你好吗的输入将输出以下内容:-
Hello:2
如何:1
是:1
您:1

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.

谢谢

推荐答案

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

这篇关于计算字符串Javascript中单词的出现次数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆