简体   繁体   English

使用Match使用Javascript计算字符串中单词的出现次数

[英]Counting occurrences of a word in a string with Javascript using match

I am trying to count occurrences of each word in longer text using the match method, but instead of result I get only an error: 我正在尝试使用match方法计算较长文本中每个单词的出现次数,但我没有得到result ,而是得到一个错误:

Cannot read property 'length' of null 无法读取null的属性“长度”

My function looks like this: 我的函数如下所示:

 const myText = "cat dog stop rain cat" myText.split(" ").forEach((word) => { const numberOfOccurrences = myText.match(/word/g).length console.log(`${word} - ${numberOfOccurrences}`) }) 

How can I repair it to get the proper result? 我该如何修理以获得正确的结果?

The regular expression is literally matching word , as variable word is never indicated. 正则表达式从字面上匹配word ,因为从不指示变量word There is no match found in the string myText so it's null, hence the error. 在字符串myText找不到匹配项,因此它为null,因此出现错误。 Try like this: 尝试这样:

myText.match(new RegExp(word, "g")).length

This uses the RegExp constructor, which takes in two arguments: the pattern and the flags. 它使用RegExp构造函数,该构造函数接受两个参数:模式和标志。 The above will pass the actual value of word instead of the literal word , and the flag g . 上面的代码将传递word的实际值而不是文字word和标志g It's equivalent to /word/g except word is correctly matched to what word is passed. 它等效于/word/g不同之处在于word与传递的word正确匹配。 See the following snippet: 请参见以下代码段:

 const myText = "cat dog stop rain cat" myText.split(" ").forEach((word) => { const numberOfOccurrences = myText.match(new RegExp(word, "g")).length console.log(`${word} - ${numberOfOccurrences}`) }) 

As others have pointed out, there are better ways to do this. 正如其他人指出的那样,有更好的方法可以做到这一点。 The output of your code above outputs the occurrence of cat twice, because it occurs twice. 上面代码的输出将出现cat两次,因为它发生了两次。 I would recommend saving your counts in an object and updating the counts at each pass, which ibrahim mahrir shows in their answer. 我建议您将计数保存在一个对象中,并在每次通过时更新计数, 易卜拉欣·马尔里尔(Ibrahim Mahrir)在其答案中显示了这些计数。 The idea is to use reduce to iterate over the split array, and reduce with the initial value of an empty object. 这个想法是使用reduce来遍历split数组,并使用空对象的初始值进行reduce。 Then, the empty object is updated with the counts of the word added by one, with initial count of zero. 然后,将空对象更新为单词计数加一,初始计数为零。

You can also try simple solution with Array#filter , without using RegExp and Array#match . 您也可以使用Array#filter尝试简单的解决方案,而不使用RegExpArray#match

 var text = "cat dog stop rain cat"; var textArr = text.split(' '); var arr = [...new Set(text.split(' '))]; arr.forEach(v => console.log(`${v} appears: ${textArr.filter(c => c == v).length} times`)); 

It's because nothing is matched. 这是因为没有匹配的东西。 There is no word word in your string. 您的字符串中没有单词word Try this: 尝试这个:

 const myText = "cat dog stop rain cat" myText.split(" ").forEach((word) => { const numberOfOccurrences = myText.match(new RegExp(word, 'g')).length; console.log(`${word} - ${numberOfOccurrences}`) }) 

Without regular expressions: 没有正则表达式:

Use a hash object like this: 使用这样的哈希对象:

 const myText = "cat dog stop rain cat" var result = myText.split(" ").reduce((hash, word) => { hash[word] = hash[word] || 0; hash[word]++; return hash; }, {}); console.log(result); 

Your expression returns an array, which has one entry, hence it always returns 1. You also have to create a regexp from the word because match takes a regexp and not a string as its argument. 您的表达式返回一个数组,该数组具有一个条目,因此它始终返回1。您还必须从单词中创建一个正则表达式,因为match将一个正则表达式而不是字符串作为其参数。

Try this instead 试试这个

 const myText = "cat dog stop word rain cat" myText.split(" ").forEach((word) => { const numberOfOccurrences = myText.match(new RegExp(word, 'g')).length; console.log(`${word} - ${numberOfOccurrences}`) }) 

I think your example is just trying to match the literal word . 我觉得你的例子只是试图匹配字面word You should use RegExp(word, "gi" instead. 您应该使用RegExp(word, "gi"代替。

const myText = "cat dog stop rain cat"

myText.split(" ").forEach((word) => {
  const numberOfOccurrences = myText.match(RegExp(word, "gi")).length
  console.log(`${word} - ${numberOfOccurrences}`)
})

I agree with above answer but if in case you looking with array of strings this will do 我同意以上答案,但是如果您要查找的是字符串数组,则可以

var textArr = ['apple', 'mango' ,'apple', 'apple' ,'cherry'];
var arr = [...new Set(textArr)];

arr.forEach(v => console.log(`${v} appears: ${textArr.filter(c => c == v).length} times`));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM