2017-02-19 76 views
0

我想指望用match方法更长的文本中的每个词的出现,但不是result我只得到一个错误计数的单词的出现在使用JavaScript字符串:使用匹配

Cannot read property 'length' of null

我功能如下:

const myText = "cat dog stop rain cat" 
 

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

我怎样才能修复它得到亲每个结果?

回答

2

正则表达式字面上匹配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遍历拆分数组,并使用空对象的初始值进行减少。然后,用添加的单词的计数更新空对象,初始计数为零。

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

1

您也可以尝试简单的解决方案,使用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`));

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

+0

你是什么意思*你的表达式返回一个数组,它有一个条目,因此它总是返回1 *? – Li357

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