如何在锚标签中自动包装文本 URL? [英] How do I automatically wrap text URLs in anchor tags?
问题描述
我有一个简单的 CMS 我为我的一个客户构建的.
这个问题是,他不是通过锚标签发布链接,而是直接复制并粘贴到文本编辑器中.
有没有办法使用 JavaScript 将这些链接包装在锚标记中?因此,当页面加载而不是看起来链接时:
http://google.com
看起来像这样
http://google.com</a>
当用户将 URL 发布到答案/问题时,Stack Overflow 实际上会这样做(如果这有助于理解我想要实现的目标).
您可以按照这些思路尝试一些事情.使用诸如 data-linkify
之类的自定义属性装饰您希望这些替换生效的标签:
something http://google.com something</div><div linkify>something</div>现在在设置了 data-linkify
的任何元素内执行替换.
$('*[data-linkify]').each(function() {$(this).html($(this).html().replace(/(?:(https?\:\/\/[^\s]+))/m, '<a href="$1">$1</a>'));});
有一些警告.这根本不是一个很好的正则表达式 — 它只是匹配以 http://
或 https://
开头的任何内容,直到第一个空格字符.寻找更好的 URL 匹配正则表达式.
此外,对 .html()
使用替换意味着它将破坏任何碰巧属于您的 data-linkify
元素的现有链接!如果您的文本链接中碰巧有双引号字符,则会创建损坏的锚元素.
您可能会考虑使用某种非常简单的标记来识别链接 — 这比猜测要好得多.
I have a simple CMS I built for a client of mine.
This issue is, instead of him posting links probably through anchor tags, he just copies and pastes it straight into the text editor.
Is there a way that these links can be wrapped in an anchor tag using JavaScript? So when the page loads instead of it looking link this:
http://google.com
It will look like this
<a href="http://google.com" target="_blank">http://google.com</a>
Stack Overflow actually does this when a user posts a URL to an answer/question (if that helps understand what I am trying to achieve).
解决方案 You could try something along these lines. Decorate the tags where you want these replacements to take effect with a custom attribute like data-linkify
:
<div data-linkify>something http://google.com something</div><div linkify>something</div>
Now perform replacements inside any element with data-linkify
set.
$('*[data-linkify]').each(function() {
$(this).html($(this).html().replace(/(?:(https?\:\/\/[^\s]+))/m, '<a href="$1">$1</a>'));
});
There are some caveats. This isn’t a great regex at all — it simply matches anything starting with http://
or https://
up until the first whitespace character. Look for a better URL matching regex.
Also, the use of replace against .html()
means that it will break any existing links that happen to fall under your data-linkify
elements! If there happen to be doublequote characters in your textual links, it will create broken anchor elements.
You might consider a very simple markup of some sort to identify links — it would be much better than guessing.
这篇关于如何在锚标签中自动包装文本 URL?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文