Je suis débutant avec jQuery.
Je veux simplement transmettre un bloc de texte à une fonction et renvoyer un ensemble d'URL contenues dans.
"J'ai besoin de saisir une URL comme http://www.something.com à partir du texte, et si therearemore.com les attrape aussi".
De l'aide? Y a-t-il un .GetUrl ()?
Note: Je suce avec des expressions régulières!
Le plugin de jQuery Wiki Text (http://www.kajabity.com/jquery-wikitext/) comprend Expressions régulières pour trouver des URL dans le texte qui peut être utilisé à cette fin.
Donc, vous avez demandé une fonction – bien, voici:
/** * 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; }
J'espère que cela aide.
RegExp est probablement le chemin à suivre, et cela devrait faire l'affaire pour vous:
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] }
Voir démo →
Vous devrez utiliser une expression régulière. Essayer:
/\i\b(http|https):\/\/(\S*)\b/i
Si vous n'êtes pas bien avec une expression régulière, je recommanderais de regarder cet outil en ligne pour les construire: http://rubular.com/ .