javascript - 如何使用 jQuery 从纯文本中提取 URL?

标签 javascript jquery url

我是 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/

相关文章:

javascript - 带有自定义列的 SimpleCart 附加信息

javascript - 测量ajax加载时间

javascript - UnderscoreJS - 如何使用迭代器之一展平对象?

api - Twitter API 资源 URL 格式中的冒号意味着什么?

javascript - JavaScript 中的依赖注入(inject)

javascript - Google map 和多个标记

javascript - 输入文件类型隐藏

javascript - 提取变量名末尾的数字

iphone - UIWbView 在 iPhone SDK 中使用 UIProgressView 加载多个 URL

http -//或/-/是有效的 URL 组件吗?