【问题标题】:Find and convert all strings starts with http & https and convert into links查找并转换所有以 http 和 https 开头的字符串并转换为链接
【发布时间】:2012-09-07 12:22:58
【问题描述】:
是否可以在一个段落中找到所有以http和https开头的字符串并使用jquery转换为链接?
我在我的网站上获得了我的 twitt 列表,所有行都以 http 和 https 开头,显示为普通字符串 [文本]。我想将它们转换为超链接。这可以用javascript,jQuery吗?
【问题讨论】:
-
如果您想在 javascript 中执行,为什么要使用 php 标记?
标签:
javascript
jquery
html
【解决方案1】:
这是检查字符串中的 URL 并将其转换为链接的代码。这也将检测以 WWW 开头的链接。希望这会有所帮助。
function Checkurl(text) {
var url1 = /(^|<|\s)(www\..+?\..+?)(\s|>|$)/g,
url2 = /(^|<|\s)(((https?|ftp):\/\/|mailto:).+?)(\s|>|$)/g;
var html = $.trim(text);
if (html) {
html = html
.replace(url1, '$1<a style="color:blue; text-decoration:underline;" target="_blank" href="http://$2">$2</a>$3')
.replace(url2, '$1<a style="color:blue; text-decoration:underline;" target="_blank" href="$2">$2</a>$5');
}
return html;
}
【解决方案3】:
jQuery WikiText Plugin 中的以下实用函数将起作用:
function findUrls( text )
{
var source = (text || '').toString();
var urlArray = [];
var url;
var matchArray;
// Regular expression to find FTP, HTTP(S) and email URLs.
var regexToken = /(((ftp|https?):\/\/)[\-\w@:%_\+.~#?,&\/\/=]+)|((mailto:)?[_.\w-]+@([\w][\w\-]+\.)+[a-zA-Z]{2,3})/g;
// Iterate through any URLs in the text.
while( (matchArray = regexToken.exec( source )) !== null )
{
var token = matchArray[0];
urlArray.push( token );
}
return urlArray;
}
JSFiddle Here.
我希望这会有所帮助!