在文档中全局更改文本节点内容
Changing text node contents globally in document
所以我有这个脚本,我用它来更改 JS 中的文本节点内容。我在 Greasemonkey 中运行这个脚本:
(function() {
var replacements, regex, key, textnodes, node, s;
replacements = {
"facebook": "channelnewsasia",
"Teh": "The",
"TEH": "THE",
};
regex = {};
for (key in replacements) {
regex[key] = new RegExp(key, 'g');
}
textnodes = document.evaluate( "//body//text()", document, null, XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE, null);
for (var i = 0; i < textnodes.snapshotLength; i++) {
node = textnodes.snapshotItem(i);
s = node.data;
for (key in replacements) {
s = s.replace(regex[key], replacements[key]);
}
node.data = s;
}
})();
效果很好。
除了我的问题是,我正在尝试将值 0 更改为 75。但是,它也会更改页面上包含在日期中的其他 0,例如今天的日期。
这不是我想要的。我只希望它自己改变 0。我该怎么做?
感谢您的帮助。
好吧,你需要正则表达式。您的脚本支持正则表达式,您只需将其放入所需替换列表中即可。
匹配单个零的正则表达式如下所示:(?:[^0-9]|^)(0)(?:[^0-9]|$)
。它的工作原理是断言非数字必须是 before/after 零 - 或字符串 beginning/end.
您可以将其放入您的替换列表中:
replacements = {
"(?:[^0-9]|^)(0)(?:[^0-9]|$)": "75",
};
或者,如果零始终由 space 分隔,请仅使用此表达式:\b0\b
代码注释:
- 请记住,对于您的系统,您必须将所有替换模板视为正则表达式。因此,当您想从字面上处理这些字符时,请不要忘记在替换中转义
(
、[
或 .
等字符。
- 无需在自调用表达式中包装整个用户脚本,用户脚本变量范围已从全局范围隐藏。
所以我有这个脚本,我用它来更改 JS 中的文本节点内容。我在 Greasemonkey 中运行这个脚本:
(function() {
var replacements, regex, key, textnodes, node, s;
replacements = {
"facebook": "channelnewsasia",
"Teh": "The",
"TEH": "THE",
};
regex = {};
for (key in replacements) {
regex[key] = new RegExp(key, 'g');
}
textnodes = document.evaluate( "//body//text()", document, null, XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE, null);
for (var i = 0; i < textnodes.snapshotLength; i++) {
node = textnodes.snapshotItem(i);
s = node.data;
for (key in replacements) {
s = s.replace(regex[key], replacements[key]);
}
node.data = s;
}
})();
效果很好。
除了我的问题是,我正在尝试将值 0 更改为 75。但是,它也会更改页面上包含在日期中的其他 0,例如今天的日期。
这不是我想要的。我只希望它自己改变 0。我该怎么做?
感谢您的帮助。
好吧,你需要正则表达式。您的脚本支持正则表达式,您只需将其放入所需替换列表中即可。
匹配单个零的正则表达式如下所示:(?:[^0-9]|^)(0)(?:[^0-9]|$)
。它的工作原理是断言非数字必须是 before/after 零 - 或字符串 beginning/end.
您可以将其放入您的替换列表中:
replacements = {
"(?:[^0-9]|^)(0)(?:[^0-9]|$)": "75",
};
或者,如果零始终由 space 分隔,请仅使用此表达式:\b0\b
代码注释:
- 请记住,对于您的系统,您必须将所有替换模板视为正则表达式。因此,当您想从字面上处理这些字符时,请不要忘记在替换中转义
(
、[
或.
等字符。 - 无需在自调用表达式中包装整个用户脚本,用户脚本变量范围已从全局范围隐藏。