[英]How can I replace a keyword but in HTML tags by JavaScript regular expression?
Here's some codes: 这是一些代码:
<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>
Hopegully, this make sense. 希望,这是有道理的。 Thanks in advance.
提前致谢。
UPDATE UPDATE
I'm sorry I've changed the code a bit. 对不起,我已经改变了一些代码。 Added addtional
http://example.com
under the a
tag. 新增addtional
http://example.com
的下a
标签。 I'd also like to put <strong>
tag here but a
's attribute. 我还想提出
<strong>
此标签,但a
的属性。
/<a.+?>(.+)</a>/
is the regex you're looking for. /<a.+?>(.+)</a>/
是你正在寻找的正则表达式。 With gi
as flags. 以
gi
为旗帜。
EDIT in response to the question update: 编辑以回应问题更新:
var para = document.getElementById('foo');
para.innerHTML = ( para.innerHTML.replace(/[^"'](http:\/\/.+?)\s/gi, '<strong>$1</strong>'));
Simplest way is to probably use 2 regexs one for the HTML encoded version and another for the non-encoded version. 最简单的方法是使用2个正则表达式,一个用于HTML编码版本,另一个用于非编码版本。
The first one would be /(http:\\/\\/example.com)/ 第一个是/(http:\\/\\/example.com)/
The second one would be /http:\\/\\/example.com(?=")/. This one uses a lookahead. It assumes you have " at the end of the URL. 第二个是/http:\\/\\/example.com(?=")/。这个使用前瞻。它假设你有“在URL的末尾。 You could also try a lookbehind but from what I recall support lookbehind is not always supported Javascript.
你也可以尝试一下lookbehind但是我记得支持lookbehind并不总是支持Javascript。 So lookahead might be the way to go.
因此,前瞻可能是要走的路。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.