我正在 jQuery 中编写一个链接化脚本,其唯一目的是获取文本区域中的所有 URL 并将其更改为可点击的链接,换句话说,在它们周围包裹一个 a href
标签。
我使用的脚本实际上工作正常,但当以“正确”的 HTML 方式添加链接并在其周围添加 a href
标记时,问题就开始了。
请访问 jsFiddle 链接查看我的脚本的运行情况。
例如,如果我在文本区域中写入:<a href=“http://google.com”>visualize.com</a>
,它会变成:<a href="<a href='http://google.com' target=‘_blank'>http://google.com</a>visualize.com</a>
,这会导致不起作用并搞乱一切。
如何仅在部分(http:// 和 www.)上应用链接,而不是在链接已包含在 a href
标记中的情况下应用链接?
最佳答案
看这个:
基本上,它首先解析标签之间的文本(但不解析 之间的文本),然后用链接正则表达式模式替换 txt。
function replaceTxtNotInA(html, regex, replace) {
//just to make the txt parse easily, without (start) or (ends) issue
html = '>' + html + '<';
//parse txt between > and < but not follow with</a
html = html.replace(/>([^<>]+)(?!<\/a)</g, function(match, txt) {
//now replace the txt
return '>' + txt.replace(regex, replace) + '<';
});
//remove the head > and tail <
return html.substring(1, html.length - 1);
}
关于javascript - Linkify/Clickable Text-URLs 但忽略那些已经包含在 "a href"中的内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20419989/