Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can you detect a url in a text area using a javascript callback function?

How can you detect a url in a textarea with JavaScript? With Facebook you can add a url and it will detect the address as soon as you finished pasting/typing it. How can this be done? I've done a lot of research on callback functions, etc. but am wondering how I can detect an actual url?

like image 657
John Doe Avatar asked Dec 16 '22 11:12

John Doe


1 Answers

If you are using jQuery the easiest way is with $.change().

Say you have a form field:

<input id="myField" type="text"/>

Now you can tie a change event to it, and at the same time find out if its a valid url:

$('#myField').keyup(function() {
    if(isUrl($(this).val()){
       //Show the url in an alert box
       alert($(this).val());
    }else{
       //do something if its not a url
    }
});

Then you would have a function that checks for a url and returns a boolean value. Note, I took this from here

function isUrl(s) {
    var regexp = /(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/
    return regexp.test(s);
}

Disclaimer: I haven't tested any of the javascript, but this should give you a good idea of how you could accomplish this.

like image 83
dmcnelis Avatar answered Dec 27 '22 20:12

dmcnelis