bea*_*ear 10 javascript url jquery
我是jQuery的初学者.
我只是想将一个文本块传递给一个函数并返回一个包含在其中的url数组.
"我需要从文本中获取像http://www.something.com这样的网址,如果有更多网站,那么就抓住它们".
有帮助吗?有.GetUrl()吗?
注意:我喜欢正则表达式!
小智 26
jQuery Wiki Text插件(http://www.kajabity.com/jquery-wikitext/)包含正则表达式,用于在文本中查找可用于此目的的URls.
所以,你要求一个功能 - 这里它是:
/**
* 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;
}
Run Code Online (Sandbox Code Playgroud)
希望能帮助到你.
RegExp可能是要走的路,这应该是你的诀窍:
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]
}
Run Code Online (Sandbox Code Playgroud)
您必须使用正则表达式。尝试:
/\i\b(http|https):\/\/(\S*)\b/i
Run Code Online (Sandbox Code Playgroud)
如果您不擅长正则表达式,我建议您查看这个在线工具来构建它们: http: //rubular.com/。