简体   繁体   中英

Find replace all in DOM error

I am trying to find all occurrences of ?sid=XXXXXXXXXX and replace them with 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:

<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. 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.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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