javascript正则表达式用链接替换一些单词,但不在现有链接中 [英] javascript regex replace some words with links, but not within existing links

查看:120
本文介绍了javascript正则表达式用链接替换一些单词,但不在现有链接中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

尝试使用相同的单词替换HTML页面中的某些单词,但作为链接到该资源的URL。
例如,将MySQL替换为< a href =http://mysql.com> MySQL< / a>

Trying to replace certain words in HTML pages with the same word but as a URL linking to that resource. For example, replace the word 'MySQL' with <a href="http://mysql.com">MySQL</a>

使用JS替换函数和正则表达式,它正在进行替换就好了。

Using the JS replace function with regex, and it's doing the replacing just fine.

但它也会替换已经属于网址的单词......这就是问题所在。

对于MySQL示例,它正在替换已经链接的MySQL文本和导致mysql.com的URL,因此打破了现有的链接。

For the MySQL example, it's replacing BOTH the "MySQL" text that's already linked, AND the URL leading to mysql.com, so breaking the already existing link.

有没有办法更新内联正则表达式(在.replace调用中),而不是替换现有的链接,即元素?

Is there a way to update the inline regex (in the .replace call) to NOT do replacing in existing links, i.e. elements?

这是替换代码:

var NewHTML = OriginalHTML
.replace(/\bJavaScript\b/gi, "<a href=\"http://js.com/\">$&</a>")
.replace(/\bMySQL\b/gi, "<a href=\"http://www.mysql.com/\">$&</a>")
;

这是完整的示例代码(尝试将其粘贴到内联中,但使用反引号看起来不正确) :
http://pastie.org/private/v4l2s2c42aqduqlopurpw

Here's the full sample code (tried to paste it inline but wasn't looking right with the backticks): http://pastie.org/private/v4l2s2c42aqduqlopurpw

浏览JS regexp参考(这里),并在正则表达式匹配中尝试了各种其他排列,如下所示,但所有这一切使它与页面上的任何单词都不匹配...
.replace (/ \b(\< a \> *!\>)JavaScript \b / i,xxxxx

Went through the JS regexp reference (here), and tried various other permutations in the regex matching, like the following, but all that does it make it not match ANY words on the page... .replace(/\b(\<a\>*!\>)JavaScript\b/i,xxxxx

以下正则表达式可以防止匹配发生在任何字面意味着触及斜线或破折号的地方......但这不是解决方案(并且它不能解决上面的mysql示例):

The following regex DOES prevent the match from happening wherever the word is literally touching a slash or a dash... but that's not the solution (and it does not fix the mysql example above):

.replace(/\b(?!\>)(?!\-)(?!\/)MySQL\b(?!\-)(?!\/)/gi, "<a href=\"http://www.mysql.com/\">$&</a>")`

我已经阅读了stackoverflow和其他地方的相关主题,但似乎无法找到这个特定的无论如何,不​​是在JavaScript中。

I've read through the related threads on stackoverflow and elsewhere, but can't seem to find this particular scenario, not in JavaScript anyway.

任何帮助都将不胜感激。 :-)

Any help would be greatly appreciated. :-)

谢谢!

推荐答案

你可以改变你的正则表达式要排除结束锚标记之前的关键字,< / a>

You could change your regex to exclude keywords that precede the end anchor tag, </a>:

.replace(/\bMySQL\b(?![^<]*?<\/a>)/gi, "<a href=\"http://www.mysql.com/\">$&</a>")

参见 jsfiddle 例如。

这篇关于javascript正则表达式用链接替换一些单词,但不在现有链接中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆