[英]javascript html text filter / linkify
I'm trying to parse some HTML for links, the idea is to replace links to images with <img>
and other links with <a>
. 我正在尝试为链接解析一些HTML,这个想法是用
<img>
替换图像的链接,并用<a>
替换其他链接。
Basically I'm looking for something like this: 基本上我正在寻找这样的东西:
https://github.com/dejan/jquery-auto_html/blob/master/jquery.auto_html.js https://github.com/dejan/jquery-auto_html/blob/master/jquery.auto_html.js
But works on HTML as well as text. 但是适用于HTML和文本。 Meaning: it should replace
http://google.com
but not <a href="http://google.com">google</a>
含义:应替换
http://google.com
而不是<a href="http://google.com">google</a>
Can I do this without lookbehinds being available in regex? 我可以在不使用正则表达式的情况下执行此操作吗? Thanks.
谢谢。
We should go from 我们应该从
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>!"
The following regex replacements will replace the links to <a>
and image links to <img>
elements. 以下正则表达式替换将替换
<a>
链接和<img>
元素的图像链接。 It excludes links that are already inside href="
or src="
etc.. 它不包括已经在
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>')
);
}
You can call it like: 您可以这样称呼它:
// 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">');
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.