2017-02-19 84 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}`) 
})