【问题标题】:javascript - replace text with tagsjavascript - 用标签替换文本
【发布时间】:2014-05-13 08:38:24
【问题描述】:

我不太了解 javascript 搜索了很长时间,但没有得到我需要的结果。

我想在页面加载这个替换

<p>---SOMERANDOMTEXT:::</p>

与

<strong>SOMERANDOMTEXT</strong>

玩了很多其他的 sn-ps..

<script type="text/javascript">
    window.onload = function() {
        function myscript() {
            input = '---';
            output='New Text';
            document.body.innerHTML = document.body.innerHTML.replace(input,output);
        }
    }
</script>

【问题讨论】:

  • 那么“---”和“:::”之间的任何内容?
  • &lt;p&gt;---SOMERANDOMTEXT:::&lt;/p&gt; 来自哪里?你自己生产吗?如果是这样,有更好的方法来做你正在做的事情。
  • 你不需要像 window.onload 那样包装函数声明。

标签: javascript text replace


【解决方案1】:

这是用&lt;strong&gt;标签替换&lt;p&gt;标签的快速且简单的方法:

var ps = document.getElementsByTagName('p');
for (var i = ps.length; i--;) {
    var strong = document.createElement('strong'),
        p = ps[i];

    while (p.firstChild) {
        strong.appendChild(p.firstChild);
    }

    p.parentNode.insertBefore(strong, p);
    p.parentNode.removeChild(p);
}

如果您需要相应地更改文本,请在 while 循环中放置类似的内容:

if (p.firstChild.nodeType === 3) {
    p.firstChild.nodeValue = p.firstChild.nodeValue.replace(/[-:]{3}/g, '');
}

演示: http://jsfiddle.net/5m9Qm/1/

【讨论】:

  • @oGeez 添加了适用于每个 &lt;p&gt; 标记的所有直接子级的解决方法。
【解决方案2】:

你需要像这样调用你的 myscript 函数 -

window.onload = function() {
  myscript();
}
function myscript() {
    var input = '---';
    var output='New Text';
    document.body.innerHTML = document.body.innerHTML.replace(input,output);
}

【讨论】:

    【解决方案3】:

    您正在声明一个函数myscript,但从未调用它。试试这个(未经测试的)代码:

    <script>
    window.onload = function(){
        var p = document.querySelector('p');
        var strong = document.createElement('strong');
        strong.innerHTML = 'replaced';
        p.parentNode.replaceChild(strong,p);
    
    })
    </script>
    

    请注意,这需要现代浏览器。

    【讨论】:

      【解决方案4】:

      您可以使用正则表达式。

      试试:

      output = document.body.innerText.replace(/[-:]{3}/g, '');
      document.body.innerHTML = document.body.innerHTML.replace(/<p>---.*:::<\/p>/, '<strong>' + output + '</strong>');
      

      DEMO

      【讨论】:

      • 或/&lt;p&gt;---.*:::&lt;\/p&gt;/ 以便您替换段落,而不是附加到它。
      • @oGeez 实际上我还没有弄清楚 OP 想要做什么,但是很好。我编辑了
      • 此解决方案将删除正文中的 所有 绑定事件 + 它非常慢。
      • 另外,我刚刚意识到,这将是您需要指定一个新值,这违背了这个想法 (AFAIA)。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-12-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多