gpt4 book ai didi

javascript - 如何使用 javascript(在 Greasemonkey 脚本中)计算某个单词在网页中出现的次数?

转载 作者:行者123 更新时间:2023-11-28 16:08:05 25 4
gpt4 key购买 nike

我是 javascript 的初学者,不知道如何计算某个单词在网页中出现的次数。

我在不同的论坛进行了研究,但没有得到帮助。我非常感谢任何实现此功能的建议或提示。

最佳答案

如果您想使用 Greasemonkey 脚本来计算单词的实例数,需要注意四件事:

  1. 使用the special \b character ,在您的正则表达式中,以确保您确实获得单词
    例如,/\bof\b/ 匹配“of”,但不匹配“offer”。

  2. 在尝试访问其属性之前,请务必检查 match() 结果不为空! match(regex).length 很多时候会抛出异常。

  3. 请注意,粗心的脚本可能会相互干扰网页。这就是其他答案之一不起作用的部分原因。 为了避免这种情况,请通过指定 @grant 指令重新打开 Greasemonkey 的沙箱。 GM 脚本现在在许多情况下默认不授予!

  4. 请注意,许多网站(例如 Google)会在 Greasemonkey 脚本触发后很久才通过 AJAX 加载内容。有很多策略可以弥补这一点。也许最简单的方法是使用计时器。

把它们放在一起,这是一个完整的脚本,可以弥补所有这些问题。您还可以see the code in action at 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; \
} \
" );

关于javascript - 如何使用 javascript(在 Greasemonkey 脚本中)计算某个单词在网页中出现的次数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14037858/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com