使用Jquery计算特定单词

时间:2014-03-16 22:03:07

标签: javascript jquery regex

我有以下HTML代码:

<ul>
<li>apples <span id="apples-density">1</span></li>
<li>pears <span id="pears-density">0</span></li>
<li>oranges <span id="oranges-density">2</span></li>
</ul>

<textarea>This is where I love to eat apples and oranges</textarea>
<textarea>I also like oranges on Sundays!</textarea>

我要实现的是,当更新textarea时(在键盘上),计算3个特定单词的密度,然后更新SPAN中的值。

但是,该页面最多可包含10个需要计数的单词以及无限数量的TEXTAREA元素。并且......每次计算的实际3个单词是不同的,因此代码必须允许某种自动化。

我可以看到它应该如何在我的脑海中起作用,但不太明白如何实现......

  1. 对textarea值执行jquery .each。
  2. 执行jquery以获取每个<li>
  3. 所以某种正则表达式匹配textarea的内容并计算单词。
  4. 更新正确的.text以显示值。

2 个答案:

答案 0 :(得分:2)

我自己的建议是:

function wordsUsed(){
    // get all the text from all the textarea elements together in one string:
    var text = $('textarea').map(function(){
        return $(this).val();
    }).get().join(' '),
        reg;
    // iterate over the span elements found in each li element:
    $('li > span').each(function(i,el){
        // cache the variable (in case you want to use it more than once):
        var that = $(el);

        // create a RegExp (regular expression) object:
            // the '\\b' is a word boundary double-escaped because it's a string;
            // we shorten the id of the current element by removing '-frequency'
            // (I didn't think 'density' was an appropriate description) to find
            // the word we're looking for;
            // 'gi' we look through the whole of the string (the 'g') and
            // ignore the case of the text (the 'i'):
        reg = new RegExp('\\b' + el.id.replace('-frequency','') + '\\b', 'gi');

        // we look for the regular-expression ('reg') matches in the string ('text'):
        var matched = text.match(reg),
            // if matched does not exist (there were no matched words) we set
            // the count to 0, otherwise we use the number of matches (length):
            matches = !matched ? 0 : matched.length;

        // setting the text of the current element:
        that.text(matches);
    });
}

$('textarea')
    // binding the keyup event-handler, using 'on()':
    .on('keyup', wordsUsed)
    // triggering the keyup event, so the count is accurate on page-load:
    .keyup();

JS Fiddle demo

上面的内容适用于(迂腐)修改过的HTML:

<ul>
    <li>apples <span id="apples-frequency"></span>
    </li>
    <li>pears <span id="pears-frequency"></span>
    </li>
     <li>oranges <span id="oranges-frequency"></span>
    </li>
</ul>
<textarea>actual text removed for brevity</textarea>
<textarea>actual text removed for brevity</textarea>

参考文献:

答案 1 :(得分:1)

// Get all the textarea values
var all_text = '';
$('textarea').each(function() {
    all_text += ' ' + $(this).text();
}
// Process each of the LIs
$('li span').each(function() {
    var word = this.id.split('-')[0]; // Get the search word
    // Convert it to a regular expression. Use 'g' option to match all occurrences.
    var regex = new RegEx('\b'+word+'\b', 'g');
    var count = all_text.match(regex).length;
    $(this).text(count);
}