我正在尝试编写一个JavaScript函数,用一个元素及其所有子元素中的另一个单词替换某个单词。
<!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>
代码已经有效,但它也取代了单词&#34; Text&#34;的一些实例。它不应该被取代。如果它是另一个单词的一部分(&#34; TextText&#34;),它不应该替换它,但如果之前有一个特殊字符,它应该替换它(&#34; bla-Text& #34;)或之后。它也不应该改变HTML属性的内容,例如&#34; href&#34;。
这个问题可以通过一个正则表达式解决,还是需要更多代码才能解决这个问题?
答案 0 :(得分:2)
我得到了一个解决方案并稍微更改了代码:
<!DOCTYPE html>
<html>
<head>
<title>Test</title>
<meta charset="UTF-8">
<script>
function replaceText(regex, to, id) {
var text = document.getElementById(id).innerHTML;
text = text.replace(new RegExp(regex, "g"), to);
document.getElementById(id).innerHTML = text;
}
window.onload = function() {
var regex = /\bText\b/;
replaceText(regex, "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>
&#13;
我希望它有所帮助:)。