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

时间:2017-02-19 23:15:46

标签: javascript regex

我正在尝试使用match方法计算较长文本中每个单词的出现次数,但不是result我只得到一个错误:

  

无法读取null

的属性'length'

我的功能如下:

const myText = "cat dog stop rain cat"

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

如何修复它以获得正确的结果?

6 个答案:

答案 0 :(得分:3)

正则表达式字面上匹配word,因为永远不会指示变量word。字符串myText中找不到匹配项,因此它为空,因此出错。试试这样:

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

这使用RegExp构造函数,它接受两个参数:模式和标志。以上内容将传递word的实际值,而不是文字word和标记g。它等同于/word/g,但wordword传递的内容正确匹配。请参阅以下代码段:



const myText = "cat dog stop rain cat"

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




正如其他人所指出的那样,有更好的方法可以做到这一点。上面代码的输出两次输出cat的出现次数,因为它出现了两次。我建议您在对象中保存计数并更新每次传递的计数,ibrahim mahrir在答案中显示。我们的想法是使用reduce迭代split数组,并使用空对象的初始值进行reduce。然后,使用加1的字的计数更新空对象,初始计数为零。

答案 1 :(得分:1)

您还可以尝试使用 Array#filter 进行简单的解决方案,而不使用RegExp Array#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`));

答案 2 :(得分:0)

因为没有匹配的东西。您的字符串中没有单词word。试试这个:



const myText = "cat dog stop rain cat"

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




没有正则表达式:

使用这样的哈希对象:



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




答案 3 :(得分:0)

您的表达式返回一个数组,该数组有一个条目,因此它总是返回1.您还必须从该单词创建一个正则表达式,因为匹配采用正则表达式而不是字符串作为其参数。

试试这个



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}`)
})




答案 4 :(得分:0)

我认为您的示例只是尝试匹配文字word。您应该使用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}`)
})

答案 5 :(得分:0)

我同意以上答案,但是如果您要查找的是字符串数组,则可以这样做

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`));