0

我想在asp.net應用程序
我有textarea的,當我輸入的文本,如果它包含像www.google.comhttp://google.com然後我希望得到textarea的值的各個環節或第一鏈路鏈接來從文本框URL鏈接。
我如何用Jquery或javascript語言實現。 當我在textarea控件中輸入文字/文本時,我想獲得每個或第一個鏈接。這裏我寫了一些代碼。如何從整個文本中獲取網站網址?

<html xmlns="http://www.w3.org/1999/xhtml"> 
<head runat="server"> 
    <title>Test Page </title> 
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js" type="text/javascript"></script> 
</head> 
<body> 
    <form id="form1" runat="server"> 
    <div> 
    <div class="innerWrap"> 
     <textarea autocomplete="off" id="txtUpdate" style="height: 48px; width: 408px;" > 
      </textarea> 
    </div> 
</div> 
<script> 
$(document).ready(function(){ 
    $('#txtUpdate').keyup(function() {  
     getURLfromText(jQuery.trim($(this).val())); 
    });  
}); 
function getURLfromText(objTxt) 
{ 
    // code 
} 
</script> 
</form> 
</body> 
</html> 

請給我正確的解決方案。 也應該是我複製並粘貼一些文本的作品。 怎麼可能。?

編輯

輸入

Down to Earth: Tracy Caldwell Dyson www.google.com 
After spending nearly six months in space, 
she is back on the ground, with two expeditions 
under her belt. http://bit.ly/dEpNHo 

輸出

Array linkarray[]=new Array(); 
linkarray[0]="www.google.com"; 
linkarray[1]="http://bit.ly/dEpNHo"; 
+0

你有一個未關閉的div BTW – corroded 2011-03-23 10:28:02

+0

@corroded對不起,我離開封閉div標籤..現在固定。 – 2011-03-23 10:30:02

回答

1

我已經在jsfiddle上發佈了一個簡短的例子。我認爲這是你正在尋找的那種東西?包含網址的正則表達式可能會接受很多你不想要的值。您可以將其切換爲您喜歡的表情。

該腳本基本上採用textarea的值,將其分割到所有空白處,然後測試數組的每個值以查看它是否使用正則表達式的url。

http://jsfiddle.net/UkCPq/1/

HTML:

<html xmlns="http://www.w3.org/1999/xhtml"> 
    <head runat="server"> 
     <title>Test Page </title> 
    </head> 
    <body> 
     <form id="form1" runat="server"> 
      <div class="innerWrap"> 
       <textarea autocomplete="off" id="txtUpdate" style="height: 48px; width: 408px;" ></textarea> 
      </div> 
     </form> 
     <p>Your urls, sir:</p> 
     <ul id="theurls"> 
      <li>:)</li> 
     </ul> 
    </body> 
</html> 

Javacript:

$(document).ready(function() { 
    $('#txtUpdate').keyup(function() { 
     getURLfromText($.trim($(this).val())); 
    }); 
}); 

function getURLfromText(objTxt) { 
    var urlpatt = new RegExp(/[[email protected]:%_\+.~#?&//=]{2,256}\.[a-z]{2,4}\b(\/[[email protected]:%_\+.~#?&//=]*)?/gi); 
    var objArray = objTxt.split(/\s/g); 
    $('#theurls').text(''); 
    $.each(objArray, function(key, value) { 
     var result = value.match(urlpatt); 
     if (result !== null) { 
      $('<li>' + result + '</li>').appendTo('#theurls'); 
     } 
    }); 
} 
+0

當我用「www.google.com」添加網址時,它沒有工作,請給我代碼的網址與「www」應該工作... – 2011-03-23 11:48:14

+0

上面的代碼與http://abcd.com很好地工作鏈接它沒有如果鏈接像www.abcd.com那樣工作。可以提供也可以使用'www'擴展名的代碼? – 2011-03-23 12:07:18

+0

我用我在這裏找到的答案和我的jsfiddle代替了正則表達式:http://stackoverflow.com/questions/3809401/javascript-url-regex 它現在應該給'www.google.com ','abcd.co.uk'等 – Sugarstack 2011-03-23 13:05:55