[英]Remove dollar sign from dom text - not from js code
I'm trying to replace all occurences of '$' (dollar sign) in a web page with another string. 我正在尝试用另一个字符串替换网页中所有出现的“ $”(美元符号)。
The problem is that there may be some <script>
tags that may contain the '$' (jQuery code) that I don't want to change. 问题是可能有一些
<script>
标记可能包含我不想更改的“ $”(jQuery代码)。
For example: 例如:
document.body.innerHTML = document.body.innerHTML.replace(/\\$/g, 'xxx');
seems to work, but also replaces '$' from any <script>$('...')...</script>
parts. 似乎有效,但也可以从任何
<script>$('...')...</script>
部分替换'$'。
Is this achievable? 这可以实现吗?
Thank you in advance. 先感谢您。
EDIT: I cannot modify the way the page is generated or change all other js parts - neither use some server-side logic. 编辑:我无法修改页面生成方式或更改所有其他js部分-都不使用某些服务器端逻辑。 I can only add some custom js code
我只能添加一些自定义js代码
You can filter out the script tags 您可以过滤出脚本标签
[].slice.call(document.body.children).forEach(function(element) {
if ( element.tagName.toLowerCase() != 'script' ) {
element.innerHTML = element.innerHTML.replace(/\$/g, 'xxx');
}
});
This is not recursive, which means it only works for script tags directly under the body tag, not script tags that are nested deeper 这不是递归的,这意味着它仅适用于body标记正下方的脚本标记,不适用于嵌套更深的脚本标记
function textNodes(main) {
var arr = [];
var loop = function(main) {
do {
if(main.hasChildNodes() && (["STYLE","SCRIPT"].indexOf(main.nodeName)==-1)){
loop(main.firstChild);
} else if(main.nodeType === 3) {
arr.push(main)
}
}
while (main = main.nextSibling);
}
loop(main);
return arr;
}
textNodes(document.body).forEach(function(a){a.textContent=a.textContent.replace(/\$/g,'€')});
Based on this DOM walking example 基于此DOM漫游示例
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.