我是 jQuery 的初学者。
我只是想将一段文本传递给函数并返回包含在其中的 url 数组。
“我需要从文本中抓取像 http://www.something.com 这样的 url,如果有 therearemore.com,那么也抓取它们”。
有什么帮助吗?有 .GetUrl() 吗?
注意:我很讨厌正则表达式!
最佳答案
jQuery Wiki 文本插件 (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;
}
希望对您有所帮助。
关于javascript - 如何使用 jQuery 从纯文本中提取 URL?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4504853/