In your replacement string, you can use $&
to include all of the replaced text. So:
replacement = original.replace(/\d{4}(?: \d{2}){4}/g, "$&*");
Example:
const original = "blah blah blah 0511 51 51 86 86 blah blah blah";
const replacement = original.replace(/\d{4}(?: \d{2}){4}/g, "$&*");
console.log(replacement);
You've asked:
Is this legal: $("body").html($("body").html().replace(/\d{4}(?: \d{2}){4}/g, "$&*"));
I am using $("body").html()
since I don't have a specific string. The whole web page content is there.
Yes, but it's a very bad idea. It tears down the page entirely (removing any event handlers or element data that may have been attached) and replaces it with a new page that's the result of parsing the HTML all over again.
Instead, use a simple recursive function to update the text nodes of the page:
const rex = /\d{4}(?: \d{2}){4}/g;
function doReplacement(element) {
for (let child = element.firstChild; child; child = child.nextSibling) {
if (child.nodeType === 3) { // A text node
child.nodeValue = child.nodeValue.replace(rex, "$&*");
} else if (child.nodeType === 1) { // An element
doReplacement(child);
}
}
}
doReplacement(document.body);
Live Example:
const rex = /\d{4}(?: \d{2}){4}/g;
function doReplacement(element) {
for (let child = element.firstChild; child; child = child.nextSibling) {
if (child.nodeType === 3) { // A text node
child.nodeValue = child.nodeValue.replace(rex, "$&*");
} else if (child.nodeType === 1) { // An element
doReplacement(child);
}
}
}
doReplacement(document.body);
blah blah blah 0511 51 51 86 86 blah blah blah
<p>
blah blah blah 0511 50 52 68 68 blah blah blah
<span>
blah blah blah 0511 49 27 67 24 blah blah blah
</span>
</p>
<div>
blah blah blah 0511 51 51 86 86 blah blah blah
<p>
blah blah blah 0511 50 52 68 68 blah blah blah
<span>
blah blah blah 0511 49 27 67 24 blah blah blah
</span>
</p>
</div>