2016-11-25 8 views
3

HTML本文中の特定の単語/ pharseの存在をカウントしたいと思います。例えば、パラグラフの中で。特別なことは、文字列ではなく、文字列自体を参照する変数とのマッチングによって数えたいと思うことです。JavaScriptでHTML本文中の選択した単語を数える方法

以下のコードはゼロのみを返します。

おそらく、それは配列としては見えないのと同じように、array_valuesを持つものです。私は初心者ですので、あらゆるヒントが重要です。

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に感謝します。

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

それはあなたがループがループどのように多くの時間を知るのに役立ちます、私はそれがproblematiqueあるソースだと思います:

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

あなたはどう思いますか?ハあなたが通信する必要がある場合は、あなた自身の質問に答える...コメントすることはできませんし、私は

関連する問題