使用markjs来计算某类的正则表达式匹配数

时间:2017-02-19 03:21:28

标签: javascript regex

我使用mark.js作为正则表达式辅助工具来突出显示字符串中的匹配项。

例如:

//negative assertions
instance.markRegExp(/not significant/g, {className: "negative"});
instance.markRegExp(/not associated/g, {className: "negative"});
instance.markRegExp(/no association/g, {className: "negative"});
//positive assertions
instance.markRegExp(/is associated/g, {className: "positive"});
instance.markRegExp(/are associated/g, {className: "positive"});
instance.markRegExp(/was associated/g, {className: "positive"});

我希望能够计算匹配类别的次数。

documentation显示了回调功能,但我不确定是否可以将其用于此目的

var options = {
"filter": function(node, term, totalCounter, counter){
    if(term === "the" && counter >= 10){
        return false;
    } else {
        return true;
    }
}
};

1 个答案:

答案 0 :(得分:2)

有点简单。您可以使用eachdone回调,两者都提供一个计数器。通过done回调,您不需要自行计算,您会收到所有商标的数量,因此对您来说更容易。此外,done回调更适合性能,因为无需在每个标记上调用该函数。

以下是代码:



var instance = new Mark(".context"),
  negativeCounter = 0,
  positiveCounter = 0;

//negative assertions
instance.markRegExp(/not significant/g, {
  className: "negative",
  done: function(counter) {
    negativeCounter += counter;
  }
});
instance.markRegExp(/not associated/g, {
  className: "negative",
  done: function(counter) {
    negativeCounter += counter;
  }
});
instance.markRegExp(/no association/g, {
  className: "negative",
  done: function(counter) {
    negativeCounter += counter;
  }
});
//positive assertions
instance.markRegExp(/is associated/g, {
  className: "positive",
  done: function(counter) {
    positiveCounter += counter;
  }
});
instance.markRegExp(/are associated/g, {
  className: "positive",
  done: function(counter) {
    positiveCounter += counter;
  }
});
instance.markRegExp(/was associated/g, {
  className: "positive",
  done: function(counter) {
    positiveCounter += counter;
  }
});

document.write("Positive counter: " + positiveCounter + ", Negative counter: " + negativeCounter);

<script src="https://cdn.jsdelivr.net/mark.js/8.8.3/mark.min.js"></script>
<div class="context">
  not significant not significant not associated no association is associated are associated was associated
</div>
&#13;
&#13;
&#13;

以下是一些注释:

  1. mark.js异步工作。从理论上讲,您应该在.mark()回调中嵌套done次调用。但是,由于您尚未启用iframes选项,因此可以使用。但如果你这样做会更安全
  2. 要减少.mark()来电的数量并使您的代码更容易,您应该为负数创建一个RegExp,为正匹配创建一个,例如:使用RegExp组。