How to get to parsing text for keywords in jQuery?

Say I had a famous speech posted on a website. What would be the best way to search for a specific keyword, for example “hello” throughout the document and save the number of occurrences as an integer? I don’t know where to start. 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 this is probably wrong, but hopefully I'm on the right track. Thanks for the help!

+3
source share
4 answers

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

var count = $("#wrapper div:contains('hello')").html().match(/hello/ig).length;
+2
source
var numberOfMatches = $('div').text().match(/hello/ig).length;
+2
source

, , div: . div, . , div...

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++; } }

jquery, .

+1

If you want 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>
+1
source

All Articles