简体   繁体   English

查找DOM中的全部替换错误

[英]Find replace all in DOM error

I am trying to find all occurrences of ?sid=XXXXXXXXXX and replace them with blank . 我正在尝试查找所有出现的?sid=XXXXXXXXXX并将其替换为blank I have this same code working elsewhere on my page finding and replacing a phone number (for example). 我在页面的其他地方也使用相同的代码来查找和替换电话号码(例如)。

I am executing the following command: 我正在执行以下命令:

document.body.innerHTML = document.body.innerHTML.replace(/?sid=XXXXXXXXXX/g, '');

A sample of the HTML it is supposed to edit is: 应该编辑的HTML示例是:

<a href="/faqs/?sid=XXXXXXXXXX">Frequently Asked Questions</a>

But I get the following error: 但是我收到以下错误:

Uncaught SyntaxError: Invalid regular expression: /?sid=XXXXXXXXXX/: Nothing to repeat

I cannot understand why it works for other strings and not this one. 我不明白为什么它适用于其他字符串而不适用于此字符串。 I understood that the above is basically treating the DOM contents as a long text string and thus the find and replace should operate like it does on the phone number example. 我了解到,以上内容基本上将DOM内容视为长文本字符串,因此查找和替换应像在电话号码示例中一样进行操作。 What am I missing? 我想念什么? Many thanks in advance for your help! 在此先感谢您的帮助!

You need to escape the ? 您需要逃脱? in your regex: 在您的正则表达式中:

document.body.innerHTML = document.body.innerHTML.replace(/\?sid=XXXXXXXXXX/g, '');

? is a special character in regular expressions so if you want to match them you need to make sure you escape them first. 是正则表达式中的特殊字符,因此,如果要匹配它们,则需要确保先将其转义。 View this MDN page to see a complete list of characters. 查看此MDN页面以查看完整的字符列表。

Don't replace the contents of body element using innerHTML replace, it can have side effects like can remove any registered event handlers etc.... instead target and replace the required 不要使用innerHTML replace替换body元素的内容,它会产生副作用,例如可以删除所有已注册的事件处理程序等。

var as = document.querySelectorAll('a[href*="?sid=XXXXXXXXXX"]');
for (var i = 0; i < as.length; i++) {
    var href = as[i].getAttribute('href');
    as[i].setAttribute('href', href.replace(/\?sid=XXXXXXXXXX/g, ''));
}

Demo: Fiddle 演示: 小提琴

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM