【发布时间】:2018-04-02 22:29:49
【问题描述】:
我正在尝试编写一个 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>
该代码已经可以使用,但它还替换了一些不应替换的“文本”一词的实例。如果它是另一个单词(“TextText”)的一部分,它不应该替换它,但如果它之前(“bla-Text”)或之后有一个特殊字符,它应该替换它。它也不应该改变 HTML 属性的内容,例如“href”。
这个问题可以用一个正则表达式解决还是我需要更多代码来解决这个问题?
【问题讨论】:
-
简短回答,您可以使用正则表达式解决此问题。您只需要在您的
from前面添加和发布您的模式,这可能是 [行首 |特殊字符 |空白] +from+ [空白 |行尾] -
如果不希望它接触html属性,则需要改为处理文本节点。
标签: javascript regex performance replace