miércoles, 9 de septiembre de 2015

Extracting url data from a textarea with jQuery and Javascript


Hello, today you can see one example of how to extract url data from a textarea with jQuery and Javascript, the objetive is detect the keyup event from textarea element and to use the match() method from javascript for url indexing with a regular expression, finally, to show the html link with the finding.


  • Simple demo, write one url, example: https://www.google.com or http://www.google.com.es or http://google.com/home/index.php ...





Example code

<!DOCTYPE HTML>
<html>
 <head>
  <meta charset="UTF-8" />
  <script type="text/javascript" src="https://code.jquery.com/jquery.js"></script>
  
  <script>
     $(function(){
   //Keyup event
   $("#textarea").on("keyup", function(){
    
    //Get the textarea text
    text = $(this).val();
    //find urls
    res = text.match(/http(s)?\:\/\/(www\.)?[a-z0-9\-\.]+[^www\.](\.[a-z]{2,4})[a-z0-9\/\-\_\.]*/i);
    //Yes results
    if (res !== null)
    {
     //Build the link
     $("#link-result").text(res[0]).attr("href", res[0]);
    }
    else
    {
     //Nothing
     $("#link-result").text('').attr("href", '');
    }
   });
     });
    </script>
  
 </head>
 <body>
   <textarea id="textarea" style="height: 150px; width: 100%;"></textarea>
   <div id="result">
   <a href="#" id="link-result" target="_blank"></a>
   </div>
 </body>
</html>


No hay comentarios: