我是一个jQuery的初学者。
我只想把一段文本传递给一个函数,并返回其中包含的网址数组。
“我需要从文本中获取像http://www.something.com这样的网址,如果有more.com,那就也抓取它们。”
有什么帮助吗?是否有.GetUrl()方法?
注意:我不擅长使用正则表达式!
我是一个jQuery的初学者。
我只想把一段文本传递给一个函数,并返回其中包含的网址数组。
“我需要从文本中获取像http://www.something.com这样的网址,如果有more.com,那就也抓取它们。”
有什么帮助吗?是否有.GetUrl()方法?
注意:我不擅长使用正则表达式!
jQuery Wiki Text插件(http://www.kajabity.com/jquery-wikitext/)包括在文本中查找URL的正则表达式,可用于此目的。
所以,您要求一个函数-好了,这就是它:
/**
* A utility function to find all URLs - FTP, HTTP(S) and Email - in a text string
* and return them in an array. Note, the URLs returned are exactly as found in the text.
*
* @param text
* the text to be searched.
* @return an array of URLs.
*/
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;
}
希望能对你有所帮助。
正则表达式可能是解决问题的途径,这个表达式可以帮助您完成任务:
var searchText = $('yourElement').text(),
// urls will be an array of URL matches
urls = searchText.match(/\b(http|https)?(:\/\/)?(\S*)\.(\w{2,4})\b/ig);
// you can then iterate through urls
for (var i = 0, il = urls.length; i < il; i++) {
// do whatever with urls[i]
}
你需要使用正则表达式。尝试一下:
/\i\b(http|https):\/\/(\S*)\b/i
如果你不擅长正则表达式,我建议你看一下这个在线工具来构建它们:http://rubular.com/。
尝试这个来获取所有类型的链接
www.aaa.aaa
www.aaa.aaa/aaa
string.match(/(www|http|https|ftp|ftps)?:?/?/?[a-zA-Z0-9-.]+.[a-zA-Z]{2,3}(/\S*)?/gi);