Javascript 如何使用 jQuery 从纯文本中提取 URL?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4504853/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I extract a URL from plain text using jQuery?
提问by bear
I'm a beginner with jQuery.
我是 jQuery 的初学者。
I simply want to pass a block of text to a function and return an array of urls contained within.
我只是想将一个文本块传递给一个函数并返回其中包含的一组 url。
"I need to grab a url like http://www.something.comfrom text, and if therearemore.com then grab those too".
“我需要从文本中获取像http://www.something.com这样的 url ,如果 therearemore.com 也获取那些”。
Any help? Is there a .GetUrl()?
有什么帮助吗?有 .GetUrl() 吗?
Note: I suck with regular expressions!
注意:我很讨厌正则表达式!
回答by Simon Williams
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.
jQuery Wiki Text 插件 (http://www.kajabity.com/jquery-wikitext/) 包括正则表达式,用于在文本中查找可用于此目的的 URls。
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;
}
Hope it helps.
希望能帮助到你。
回答by mVChr
RegExp is probably the way to go, and this should do the trick for you:
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]
}
回答by Kevin Sylvestre
You will have to use a regular expression. Try:
您将不得不使用正则表达式。尝试:
/\i\b(http|https):\/\/(\S*)\b/i
If you aren't good with regular expression, I'd recommend taking a look at this online tool for building them: http://rubular.com/.
如果您不擅长正则表达式,我建议您查看这个用于构建它们的在线工具:http: //rubular.com/。
回答by Bhushan Patil
Try this to get all type of links
试试这个来获取所有类型的链接
www.aaa.aaa
www.aaa.aaa
www.aaa.aaa/aaa
www.aaa.aaa/aaa
string.match(/(www|http|https|ftp|ftps)?:?/?/?[a-zA-Z0-9-.]+.[a-zA-Z]{2,3}(/\S*)?/gi);
string.match(/(www|http|https|ftp|ftps)?:?/?/?[a-zA-Z0-9-.]+.[a-zA-Z]{2,3}(/ \S*)?/gi);