Greasemonkey Javascript:如何遍历所有文本并仅更改整个单词?

Greasemonkey Javascript: how to loop through all text and change only whole words?

当我加载一个网页(恰好在 Reddit 上)时,我想循环遍历所有可见文本(不是标签或属性或 的内容),并将一个字符串更改为另一个字符串,但只能是整个单词.我是 Javascript 和 Greasemonkey 的新手,请耐心等待。我通过查看代码学得最好。此代码有效,但我想使用类似下面的内容来存储 'old' 字符串和 'new' 字符串。这将使任何用户更容易更新字符串。格式:'old string':'new string'.

var arReplacements = {
  "Woman's":"Pink's",
  "woman": "pink",
  "women": "pinks",
  "Woman":"Pink",
  "Women":"Pink",

  "man's": "blue's",
  "Man's":"Blue's",
  "men's":"blue's",
  "Men's":"Blue's",
  "men": "blues",
  "man": "blue",
  "Men": "Blues",
  "Man":"Blue",

  "Girl's":"Pink's",
  "girl's":"pink's",
  "girl": "pink",
  "Girl":"Pink",
  };

如果您查看我的脚本,我会将许多字符串更改为其他字符串,因此必须从变量构建正则表达式。例如:

"man" to "blue"
"men" to "blues"
"Man" to "Blue"
"Men" to "Blues"
"man's" to "blue's"
"Man's" to "Blue's"

目前在函数test2()中,新旧单词存储在fromArr[]和toArr[]中。

INPUT:很多人都很有礼貌。

将 'man' 更改为 'blue'。

预期输出:许多蓝色都有礼貌。 (注意 'manners' 没有改变。)

当前代码在这里:https://github.com/bulrush15/gmscripts

是Changer.user.js文件。代码有点乱,但看看 test2() 函数,现在是 运行。

使用 Greasemonkey 加载此页面并打开此脚本进行测试:https://www.reddit.com/r/test/comments/3kdyfd/test_of_man_and_manners/

谢谢!

它将与单词边界一起工作 \b 并且正则表达式 /\bman(?=\b|')/ig

document.write('Many a man has good manners Man Man\'s'.replace(/\bman(?=\b|')/ig, 'blue'));

Test your Regex here