Javascript HTML文本过滤/链接

javascript html text filter / linkify

本文关键字:链接 文本过滤 HTML Javascript      更新时间:2023-09-26

我试图解析一些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>!"

以下regex替换将替换指向<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">');