繁体   English   中英

如何通过JavaScript正则表达式替换HTML标签中的关键字?

[英]How can I replace a keyword but in HTML tags by JavaScript regular expression?

这是一些代码:

<p id="para">
    This is my webpage:
    <a href="http://example.com">
        http://example.com
    </a>
    http://example.com
</p>

<script type="text/javascript">
    var para = document.getElementById('para').innerHTML;
    var re = new RegExp(/(http:\/\/example\.com)/, 'gi'); // Should be fixed

    para = para.replace(re, '<strong>$1</strong>');

    // Result HTML code will be something like below:
    //
    // <p id="para">
    //     This is my webpage:
    //     <a href="&lt;strong&gt;http://example.com&lt;/strong&gt;">
    //         <strong>http://example.com</strong>
    //     </a>
    //     <strong>http://example.com</strong>
    // </p>
    //
    // So, I don't want to change the tag attribute,
    // and want to write regexp to avoid this problem.
</script>

希望,这是有道理的。 提前致谢。

UPDATE

对不起,我已经改变了一些代码。 新增addtional http://example.com的下a标签。 我还想提出<strong>此标签,但a的属性。

/<a.+?>(.+)</a>/是你正在寻找的正则表达式。 gi为旗帜。

编辑以回应问题更新:

var para = document.getElementById('foo');
para.innerHTML = ( para.innerHTML.replace(/[^"'](http:\/\/.+?)\s/gi, '<strong>$1</strong>'));

最简单的方法是使用2个正则表达式,一个用于HTML编码版本,另一个用于非编码版本。

第一个是/(http:\\/\\/example.com)/

第二个是/http:\\/\\/example.com(?=")/。这个使用前瞻。它假设你有“在URL的末尾。 你也可以尝试一下lookbehind但是我记得支持lookbehind并不总是支持Javascript。 因此,前瞻可能是要走的路。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM