有谁知道有一个脚本可以选择对 URL 的所有文本引用并自动将其替换为指向这些位置的锚标记?
For example:
http://www.google.com
would automatically turn into
<a href="http://www.google.com">http://www.google.com</a>
注意:我想要这个是因为我不想浏览所有内容并用锚标签包裹它们。
NOTE:该脚本的更新和更正版本现已提供:https://github.com/maranomynet/linkify(GPL/麻省理工学院许可证)
嗯...对我来说这似乎是 jQuery 的完美任务。
......这样的事情从我的脑海中浮现出来:
// Define: Linkify plugin
(function($){
var url1 = /(^|<|\s)(www\..+?\..+?)(\s|>|$)/g,
url2 = /(^|<|\s)(((https?|ftp):\/\/|mailto:).+?)(\s|>|$)/g,
linkifyThis = function () {
var childNodes = this.childNodes,
i = childNodes.length;
while(i--)
{
var n = childNodes[i];
if (n.nodeType == 3) {
var html = $.trim(n.nodeValue);
if (html)
{
html = html.replace(/&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(url1, '$1<a href="http://$2">$2</a>$3')
.replace(url2, '$1<a href="$2">$2</a>$5');
$(n).after(html).remove();
}
}
else if (n.nodeType == 1 && !/^(a|button|textarea)$/i.test(n.tagName)) {
linkifyThis.call(n);
}
}
};
$.fn.linkify = function () {
return this.each(linkifyThis);
};
})(jQuery);
// Usage example:
jQuery('div.textbody').linkify();
它尝试将所有出现的以下内容转换为链接:
www.example.com/path
http://www.example.com/path
mailto:[email protected]
ftp://www.server.com/path
- ...以上所有内容都包含在尖括号中(即
<
...>
)
享受 :-)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)