Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Count how many times a specific value appears in a table

I've an html table that contains a list of names within sentences, which are inside <td> elements (i.e. <td>Mike (Jeremy's father) used to play piano</td> or <td>The only one who speaks french is Desmond, but Mike speaks very well spanish</td>). I would like to count how many times a specific name appears within the entire table. I need this to be done through javascript/jquery, and not via php. Any help would be appriciated!

like image 807
mat Avatar asked Dec 01 '25 02:12

mat


1 Answers

You could use

var nbMikeInTheTable = (' '+$('table').text()+' ').split('Mike').length-1;

(the added ' ' are for the compatibility with the buggy implementation of split on IE)

Or, if you want to be sure it's the entire word and it's not cut by HTML

 var nbMikeInTheTable = $('table').html().split(/\W+/).filter(
     function(v){return v=="Mike"}
 ).length;

If you want to guard against end of words and end of cells and be sure it's not part of an attribute of a td, it's a little more complex :

var nbTimesMikeIsInTheTable = $('table td').map(function(){
    return $(this).text().split(/\W+/).filter(function(v){return v=="Mike"}).length
}).toArray().reduce(function(p,v){return p+v});

This isn't elegant but is probably not needed ;)

Demonstration (open the console)

like image 138
Denys Séguret Avatar answered Dec 02 '25 16:12

Denys Séguret