I am trying to write a JavaScript function which replaces a certain word by another word in an element and all its child elements.
<!DOCTYPE html>
<html>
<head>
<title>Test</title>
<meta charset="UTF-8">
<script>
function replaceText(from, to, id) {
var text = document.getElementById(id).innerHTML;
text = text.replace(new RegExp(from, "g"), to);
document.getElementById(id).innerHTML = text;
}
window.onload = function() {
replaceText("Text", "Tekst", "test");
}
</script>
</head>
<body>
<!-- This div should look the same as... -->
<div id="test"><p title="lorem Text ipsum">lorem <span>Text ipsum</span> dolor sit TextText amet, consectetur text adipiscing elit, bla-Text sed do eiusmod blaText <b>Text</b> tempor incididunt <a href="/Text">Text</a> ut labore et dolore magna Text aliqua.</p></div>
<!-- ... as this div in the browser. -->
<div><p title="lorem Text ipsum">lorem <span>Tekst ipsum</span> dolor sit TextText amet, consectetur text adipiscing elit, bla-Tekst sed do eiusmod blaText <b>Tekst</b> tempor incididunt <a href="/Text">Tekst</a> ut labore et dolore magna Tekst aliqua.</p></div>
</body>
</html>
The code already works, but it also replaces a few instances of the word "Text" that it shouldn't replace. It shouldn't replace it if it's a part of another word ("TextText"), but it should replace it if there is a special character right before ("bla-Text") or after it. It also shouldn't change the content of HTML attributes, such as "href".
Can this problem solved with one regular expression or do I need more code to solve this problem?