[英]How to count the number of times a word appears in a webpage using javascript (in a Greasemonkey script)?
我是 javascript 初学者,不知道如何计算一个单词在网页中出现的次数。
我在不同的论坛上进行了研究,但没有得到任何帮助。 我非常感谢任何实现此功能的建议或提示。
如果您想使用 Greasemonkey 脚本来计算单词的实例数,则需要注意四件事:
在您的正则表达式中使用特殊的\\b
字符以确保您确实得到了words 。
例如, /\\bof\\b/
匹配“of”但不匹配“offer”。
在尝试访问它们的属性之前,请始终检查match()
结果是否为空! match(regex).length
大部分时间都会抛出异常。
请注意,粗心的脚本可能会相互干扰网页。 这是其他答案之一不起作用的部分原因。
为避免这种情况,请通过指定@grant
指令重新打开 Greasemonkey 的沙箱。 GM 脚本现在默认在许多情况下不grant none
权限!
请注意,许多网站(例如 Google)在 Greasemonkey 脚本触发很久之后,都会通过 AJAX 加载内容。 有很多策略可以弥补这一点。 也许最直接的是使用计时器。
综上所述,这里有一个完整的脚本,可以弥补所有这些问题。 您还可以在 jsFiddle 中查看正在运行的代码:
// ==UserScript==
// @name _Show word counts
// @include http://YOUR_SERVER.COM/YOUR_PATH/*
// @require http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js
// @grant GM_addStyle
// ==/UserScript==
/*- The @grant directive is needed to work around a design change
introduced in GM 1.0. It restores the sandbox.
*/
$("body").append ('<div id="gmWordCount"></div>');
checkWordCount (); //-- Initial run, works for static HTML only.
//--- Check for AJAX loaded words... Over twice a sec is plenty fast.
var wordChkTimer = setInterval (checkWordCount, 444);
function checkWordCount () {
//--- Search for "of" as a whole word.
var wordStr = "of";
var wordRegex = new RegExp ("\\b" + wordStr + "\\b", "gi");
var matchRez = $(document.body).text ().match (wordRegex);
var wordCount = matchRez ? matchRez.length : 0;
//--- Display the results.
var countReport = '';
switch (wordCount) {
case 0:
countReport = '"of" was not found!'
break;
case 1:
countReport = '"of" was found one time.'
break;
default:
countReport = '"of" was found ' + wordCount + ' times.'
break;
}
//--- Display results to the user.
$("#gmWordCount").text (countReport);
}
//--- Position and style the display output,
GM_addStyle ( " \
#gmWordCount { \
background: orange; \
position: fixed; \
top: 0; \
left: 0; \
width: 100%; \
z-index: 6666; \
} \
" );
这对你来说是一个开始。 就目前而言,它将匹配存在于其他单词中的实例,例如“咖啡”将计入“of”,它会干扰其他页面,我还没有检查 jQuery 是否已经存在。 因此,您实际上需要自己做一些工作。
// ==UserScript==
// @name Count words
// @namespace count
// @version 1
// @require http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js
// ==/UserScript==
$(function(){
var word='of'; // put your word here
var regex = new RegExp(word, "gi")
alert ($('body').text().match(regex).length);
});
var text = document.body.textContent
.replace(/\r?\n?/g, "") // removes lines
.replace(/\s{2,}/g, " "), // removes duplicate spaces
word = new RegExp("of", "gi");
alert(text.match(word).length);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.