[英]How can I write a javascript regular expression to replace hyperlinks in this format [*](*) with html hyperlinks?
[英]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="<strong>http://example.com</strong>">
// <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.