【问题标题】:Replacing word by another word in certain cases在某些情况下用另一个单词替换单词
【发布时间】: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


【解决方案1】:

我得到了一个解决方案并稍微更改了代码:

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

希望对你有帮助:)

【讨论】:

  • 这也会改变 a-tag 中的 href。
  • 是的,但问题是 JavaScript 现在不支持负向回溯,而这正是我们需要的,请看这里:stackoverflow.com/questions/30118815/…。所以你不应该在标签中使用 href 文本作为普通文本
猜你喜欢
  • 2015-03-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-02-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多