JavaScript HTML文本过滤器/链接化

4

我正在尝试解析一些HTML链接,想法是将图片链接替换为<img>,其他链接替换为<a>

基本上我正在寻找这样的东西:

https://github.com/dejan/jquery-auto_html/blob/master/jquery.auto_html.js

但它可以在HTML和文本中工作。也就是说:它应该替换http://google.com,但不应替换<a href="http://google.com">google</a>

我可以在正则表达式中没有后顾的情况下做到这一点吗?谢谢。

我们应该从这里开始:

html = "Here is a great site: http://google.com!"
convert(html)
> "Here is a great site: <a href=\"http://google.com\">google</a>!"

html = "Here is a great site: <a href=\"http://google.com\">google</a>!"
convert(html)
> "Here is a great site: <a href=\"http://google.com\">google</a>!"

回顾先行断言是最好的选择。确认 href=" 部分存在,因此使用这个模式查找文本是最好的方法。 - Shiplu Mokaddim
@Shiplu 是的,我知道,只是 JavaScript 不支持 lookbehind。 - Harry
你能否编辑你的问题,明确说明你想要转换哪些HTML?我很困惑,不知道你是要将a元素转换为img元素,还是将文本转换为imga元素。 - mrtsherman
@mrtsherman 添加了一些例子。 - Harry
1个回答

2
以下正则表达式替换将会替换链接为<a>和图片链接为<img>元素。它会排除已经在href="src="等内部的链接。
function replaceStuff(html) {
  return html
         .replace(/[^\"]http(.*)\.(png|jpg|jpeg|gif)/g, ' <img src="http$1.$2">'
         .replace(/[^\"]http(.*)\.([a-zA-Z]*)/g, ' <a href="http$1.$2">http$1.$2</a>')
         );
}

您可以这样调用它:
// will replace the link to <a>
replaceStuff('Hello http://google.com');

// will not replace anything
replaceStuff('Hello <a href="http://google.com">ff</a>');

// will replace image link to <img>
replaceStuff('Hello http://google.com/image.png');

// will not replace anything
replaceStuff('Hello <img src="http://google.com/image.png">');

它排除引号中的链接。我最喜欢的网站是"http://axels-fahrradladen.de"将不会有任何改变。 - Matmarbon
是的,我编写它以排除引号中的链接。正则表达式可以扩展为仅过滤href="..src="..而不是引号中的所有内容。 - techfoobar
克隆并纠正了jsbin,链接在这里:http://jsbin.com/uyixoq/2 - 来源:http://jsbin.com/uyixoq/2/edit#source - techfoobar
第一个replace()后面缺少一个括号,第二个后面多了一个闭合括号! :-) - techfoobar

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接