首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何计算特定字符串中的特定单词?

如何计算特定字符串中的特定单词?
EN

Stack Overflow用户
提问于 2022-02-27 15:37:31
回答 5查看 220关注 0票数 0

我对javascript很陌生,还在学习一些数据类型,我得到了一些我无法理解的内容,请帮助我。

练习问题:

“爱是这个世界上最好的东西。有些人找到了他们的爱,有些人仍然在寻找他们的爱。”数一数这个句子中这个词的个数。

所以我尝试了一些基本的方法,比如,

  1. 匹配
  2. 搜索
  3. 拆分

我数不清爱和给予爱的词的索引。

我如何编码这个以找到答案?

EN

回答 5

Stack Overflow用户

发布于 2022-02-27 15:42:37

这应该能行。

代码语言:javascript
运行
复制
let sentence = "Love is the best thing in this world. 
Some found their love and some are still looking for their love."

console.log(sentence.split("love").length)
票数 0
EN

Stack Overflow用户

发布于 2022-02-27 15:42:54

这应该能行

代码语言:javascript
运行
复制
const sentence = 'Love is the best thing in this world. Some found their love and some are still looking for their love.'
const occurrences = sentence.match(/love/gi); // (g is is for match all occurrences, i is for case insensitive)
console.log("number of occurrences of 'love'", occurrences.length)
票数 0
EN

Stack Overflow用户

发布于 2022-02-27 15:55:06

为了使它更加通用,并显示使用了reduce:

代码语言:javascript
运行
复制
const data = "Love is the best thing in this world. Some found their love and some are still looking for their love"

const dataArray = data.split(' ');

const wordMap = dataArray.reduce((result, word) => {
    result[word.toLowerCase() ]= result[word.toLowerCase() ] ? result[word] + 1 : 1;
    return result
}, {});

console.log(wordMap["love"])
console.log(wordMap["is"])
console.log(wordMap["best"])

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/71286099

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档