Hello. I would like to know how I can find multiple URL's in a textarea then use "for each" to run code that I want to run on each URL.
For example, if the user typed this into the textarea "Hello, please visit http://example.com and http://google.com" then I would want to be able to find each URL in the textarea and run the code that I want to run on each URL.
Thanks for that, I know http:// is optional but if it was compulsory in my website then is there a way I can use "for each" for everything that begins with http:// without spaces?
How can I run code on every item in an array? For example:
Code:
function isUrl(s) {
var regexp = /(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/
return regexp.test(s);
}
function findURLs(){
var array = document.getElementById("textarea").split(" ");
// for each item in array, run the below code
if(isUrl(array[ITEM IN ARRAY]){
document.getElementById("textarea").replace(array[ITEM IN ARRAY], "URL REPLACEMENT HERE");
}
}
How can I run the isURL() function on each item in the array and how do I show the current item (e.g. array[CURRENT ITEM])?
Please help, and thanks Declan1991 for the regexp.
Last edited by Chris252; 05-11-2009 at 06:28 AM.
Reason: Fixed an incorrect piece of code
I have not got this working. For those who stumble across this thread in the future, here is my code.
Code:
function isUrl(s) {
var regexp = /(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/
return regexp.test(s);
}
function findURLs(){
var array = document.getElementById("textarea").split(" ");
for (var n = 0; n < array.length; n++){
if(isUrl(array[n]){
document.getElementById("textarea").replace(array[n], "URL REPLACEMENT HERE");
}
}
}
Last edited by Chris252; 05-11-2009 at 06:44 AM.
Reason: Added [CODE] tags
A variant is possible without jQuery and without loop with something like this (only a demo)
Code:
function findURLs(){
var txt = document.getElementById("textarea");
// Your reg exp with a g at the end
var rgx= = /(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/g;
// A replace which call an anonymous function for each URL
newTxt=txt.replace(rgx,function(){var i,c='';for (i=0;i<arguments.length;i++) c=+'\n'+arguments[i];
// The first argument is the matched pattern and the other the sub-patterns defined by brakets
alert(c);
//...
// The return value replace the matched pattern
return "URL REPLACEMENT HERE";
});
}
Bookmarks