如何使用jQuery从纯文本中提取URL? [英] How do I extract a URL from plain text using jQuery?
问题描述
我是jQuery的初学者。
I'm a beginner with jQuery.
我只是想将一个文本块传递给一个函数并返回一个包含在其中的url数组。
I simply want to pass a block of text to a function and return an array of urls contained within.
我需要获取像 http://www.something.com这样的网址来自文本,如果有moremore,那么也抓住那些。
"I need to grab a url like http://www.something.com from text, and if therearemore.com then grab those too".
任何帮助?有.GetUrl()吗?
Any help? Is there a .GetUrl()?
注意:我用正则表达式吮吸!
Note: I suck with regular expressions!
推荐答案
jQuery Wiki Text插件(http://www.kajabity.com/jquery-wikitext/)包含正则表达式,用于查找可用于此目的的文本中的URls。
The jQuery Wiki Text plugin (http://www.kajabity.com/jquery-wikitext/) includes Regular Expressions to find URls in text which can be used for the purpose.
所以,你问了一个函数 - 这里是:
So, you asked for a function - well here it is:
/**
* 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;
}
希望有所帮助。
这篇关于如何使用jQuery从纯文本中提取URL?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!