0

How I can use Jquery to find http:// or www. and ends with .com, .org, .edu store that as a variable and wrap it in like:

<a href="variable">  <a/>

I have a textarea and when people put in links, I would like to then make them into hyperlinks once they are posted.

double-beep
  • 5,031
  • 17
  • 33
  • 41
Xtian
  • 3,535
  • 11
  • 55
  • 91
  • 1
    If you don't want to do it until they are posted, you want to do this with server-side code rather than with jquery. If you're using JS to create a preview of the post before submission, then using jquery would make sense. – intuited Jun 08 '10 at 02:56

2 Answers2

1

lets say the text area contains,

http://site1.com/uri/
http://site2.net/uri
http://site3.org/uri
http://site4.co.uk/uri
http://site5.ws/uri

The first thing i would do is bind an even for keyup on the textarea

$('#addLinks').bind('keyup',function(){
    var _data = $(this).val();
    //Then i would try and split the spaces and carriages 
    _array = _data.split('\n|\r\n|\s|,'); //Split by returns,new lines,spaces,commas.
    var _regexp = /(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/
    $(_array).each(function(value){
       //Now i will check the URL is valid
       if(_regex.test(value))
       {
           //Valid URL so i will then append it to the links container
           //Here you can do e
           $('<a></a>').attr('href',value).val(value).appendTo('.linksContainer');
       }
    })
});

Something along them lines!

Regex borrowed from: http://snippets.dzone.com/posts/show/452

RobertPitt
  • 56,863
  • 21
  • 114
  • 161
0

roll your own way:

var foo = $('textarea selector').val();

then use a regular expression to get what you want. then stick it back into the textarea

$('textarea selector').val('http://thenewlink');

easy plugin way:

7 jQuery Plugins to Manipulate TEXTAREAs

pxl
  • 1,297
  • 10
  • 16