3

Say I had a famous speech posted on a website. What would be the best way to go about searching for a given keyword, say 'hello' throughout the entire document and save the number of occurrences as an integer? I don't really know where to start on this one. Should I use something like...

var wordcount;
$('#wrapper').each(function(e)

{
     $("div:contains('hello')"){ //all content will be in the wrapper div
     wordcount++;
});
});

I know that probably isn't right, but hopefully I'm on the right track. Thanks for the help!

Šime Vidas
  • 182,163
  • 62
  • 281
  • 385
dzilla
  • 782
  • 5
  • 13
  • 22

4 Answers4

2

The easiest way is to just return the length of a RegExp match:

var count = $("#wrapper div:contains('hello')").html().match(/hello/ig).length;
mVChr
  • 49,587
  • 11
  • 107
  • 104
2
var numberOfMatches = $('div').text().match(/hello/ig).length;
John Strickler
  • 25,151
  • 4
  • 52
  • 68
  • well, that was easy then! was i even anywhere near the ball park on my iteration? – dzilla May 02 '11 at 19:29
  • i'd like to say yes, but you were pretty far off. $('div:contains('hello') returns a jQuery object of all div's that contain the text 'hello'. Putting it inside the .each() function just ensured that it was called N times. To call it within the context of #erapper you should have done $('div', this) or $('#wrapper div') still nowhere near where you wanted to be though... – John Strickler May 02 '11 at 19:31
  • 1
    I'm not sure if `.text()` is the most appropriate here as it combines the text of the elements. Consider `$("I've been to hellonce").text() = "I've been to hellonce"` which will match the regex. `.html()` would be more appropriate, or maybe adding word boundaries to the regex `/\bhello\b/ig` – Dan Manastireanu May 02 '11 at 19:42
  • @Dan, that's true. What if I search for 'span' thought? We'd be matching text inside the HTML tags. So we'd have to change the RegEx to account for this now... "RegEx cannot be used to parse HTML" - see http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags. What I was trying to do was provide a short one liner for dzilla so he could be on the right path. – John Strickler May 02 '11 at 20:15
  • @John I'm familiar with that post. I wasn't trying to drag down your answer, just offering suggestions. At least the word boundary idea is applicable here. Anyway I doubt that he'll be searching for html elements, I don't know any famous quotes about them :) – Dan Manastireanu May 02 '11 at 20:28
1

Well unfortunately, that div:contains is only going to fire once. It is looking for all divs that contain that text. Unless you have every word wrapped in a div tag...

var text = $('#wrapper').text();
var words[] = text.split(' ');
var count = 0;
for(var i=0; i<words.length; i++){ if(words[i].IndexOf("TheWord") >= 0){ count++; } }

This is a non jquery method, but it should work for you.

Avisra
  • 740
  • 5
  • 14
1

If you're wanting to do this interactively (i.e., with a dynamic string), then this implementation is idiomatic:

http://jsfiddle.net/entropo/S5uTg/

JS ...

$("#keyword").keyup(function() {
    var value = $(this).val(),
        re = new RegExp(value, 'ig'),
        count = $("#speech").text().match(re).length;
    $("#result").text("Occurences: " + count);
});

HTML ...

<div id="search-form">
    <legend>Search through this text</legend>
    <label for="keyword">Keyword</label>
    <input id="keyword" name="keyword" type="search"
        placeholder="e.g. - today" required="" autofocus="" />

    <div id="result"></div>            
</div>
entropo
  • 2,481
  • 15
  • 15