我正在使用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;
}
}
};
最佳答案
这有点简单。您可以使用 each
或 done
回调,两者都提供计数器。使用 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>
以下是一些注意事项:
- mark.js 异步工作。理论上,您应该将
.mark()
调用嵌套在done
回调中。但是,由于您尚未启用 iframes 选项,因此它可以工作。但这样做更安全 - 为了减少
.mark()
调用量并使代码更简单,您应该为负匹配创建一个正则表达式,为正匹配创建一个正则表达式,例如使用正则表达式组。
关于javascript - 使用markjs统计某个类的正则表达式匹配数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42323276/