2016-11-25 48 views
3

我想要計算HTML正文中特定單詞/ pharse的出現次數。例如在一段中。特別的是,我想通過匹配一個變量進行計數 - 它指的是字符串,而不是字符串本身。如何使用JavaScript計算HTML正文中的選定單詞

下面的代碼只返回零。

也許這是與array_values - >喜歡它沒有看到它作爲一個數組。我是一個begginer,所以每一個提示都很重要。

var array_values = document.getElementsByClassName('a'); // <p class="a"> A paragraph that contains some text. 

var chosenWord = document.getElementById("input").value; // a word that i would like to count (how many times it occours in paragraph) 

var count = 0; 
for (var i = 0; i < array_values.length; i++) { 
    if (array_values[i] == chosenWord) 
     count++; 
} 

alert("The word " + chosenWord + "occours " + count + "times"); 

回答

1

一個小小的變化,它的工作原理!改變是在第一個變量的聲明中 - 必須添加innerHTML - 如果沒有它,我們會創建一個[我認爲不能用於此目的]的[HTML OBJECT]。感謝Antoine創建了修剪和分割以及一個Array。

var lines = document.getElementById("text").innerHTML.trim().split(" "); // A paragraph that contains some text 

var chosenWord = document.getElementById("input").value; // a word that i would like to count (how many times it occours in paragraph) 

var texts = []; 
    for (var i=0; i < lines.length; i++) { 
    //only push this line if it contains a non whitespace character. 
     if (/\S/.test(lines[i])) { 
      texts.push($.trim(lines[i])); 
     } 
    } 

alert(JSON.stringify(texts)); // the block is creating an array of words from selected DIV. Alert is just to show you an array. 


var count = 0; 
for (var i = 0; i < texts.length; i++) { 
    if texts[i] == chosenWord) 
     count++; 
} 

alert("The word " + chosenWord + "occours " + count + "times"); 
2

代碼似乎很好,首先,補充一點:

var totalIteration = 0; 
var count = 0; 
for (var i = 0; i < array_values.length; i++) { 
    totalIteration ++; 
    if (array_values[i] == chosenWord) 
     count++; 
} 

alert("The word " + chosenWord + "occours " + count + "times in a loop that looped " + totalIteration + " times); 

它會幫助你知道循環多少時間循環,我認爲它是人問題的根源:

var array_values = document.getElementsByClassName('a'); 

你覺得呢?哈,你無法評論...回答自己的問題,如果你需要溝通,我會

相關問題