Wojtek
Wojtek

Reputation: 51

How to count selected word in HTML body by JavaScript

I would like to count occurency of specific word/pharse in a HTML body. For example in a paragraph. The special thing is that i want to count by matching with a variable - that refers to string, not a string itself.

The code below returns only zeroes.

Maybe it's something with array_values --> like it doesn't see it as an array. I'm a begginer so every hint matters.

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

Upvotes: 3

Views: 861

Answers (3)

Wojtek
Wojtek

Reputation: 51

One minor change and it works! The change is in declaration of first variable - had to add innerHTML - without it we create an [HTML OBJECT] which (I suppose) can't be used for that purpose. Thanks to Antoine who created trim and split and an 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");

Upvotes: 2

Antoine Pelletier
Antoine Pelletier

Reputation: 3316

Look at this :

Convert textarea value to javascript array (separated by new lines)

Instead of splitting on what's in the question, just split on (" ")

Upvotes: 1

Antoine Pelletier
Antoine Pelletier

Reputation: 3316

The code seems fine, first, add this :

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

it will help you know how many time the loop looped, i think it's the source that is problematique :

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

What do you think ? Ha you can't comment... answer your own question if you need to communicate and i will transfer it in the comments

Upvotes: 1

Related Questions