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>
source
share