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

  <meta charset="UTF-8" />
  <script type="text/javascript" src="https://code.jquery.com/jquery.js"></script>
   //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]);
     $("#link-result").text('').attr("href", '');
   <textarea id="textarea" style="height: 150px; width: 100%;"></textarea>
   <div id="result">
   <a href="#" id="link-result" target="_blank"></a>

No hay comentarios: