2017-04-04 55 views
0

我不知道如何獲得div contenteditable中的第一個鏈接(文本類型)。在我的事業部,我的價值是:獲取Div中contenteditable的第一個鏈接用Javascript

<div id="content" contenteditable="true" value="http://google.com and other string but i only get the link"></div> 

我想只有http://google.com

而第二個問題,當值http://google.com http://yahoo.com我想只得到第一個鏈接http://google.com

我使用jQuery與key contenteditable中的關鍵事件。希望你能幫助我,謝謝!

更新我的代碼:

$(document).ready(function() 
{ 
    $("#content").keyup(function(){ 
    var link = $("content").text(); 
    console.log(link); 
    }); 
} 

和HTML

<div id="content" contenteditable="true"></div> 
+0

你可以在Jsfiddle中做一個演示,它會更詳細地描述它。 – Manwal

+0

顯然你有一些代碼,請顯示它的相關部分。 – Teemu

+0

是的,對不起,我會更新我的問題 –

回答

0

考慮下面的代碼:

$(document).ready(function() { 
    $("#content").keyup(function(){ 
    var link = $("#content").text().match(/(https?:\/\/(?:www\.|(?!www))[a-zA-Z0-9][a-zA-Z0-9-]+[a-zA-Z0-9]\.[^\s]{2,}|www\.[a-zA-Z0-9][a-zA-Z0-9-]+[a-zA-Z0-9]\.[^\s]{2,}|https?:\/\/(?:www\.|(?!www))[a-zA-Z0-9]\.[^\s]{2,}|www\.[a-zA-Z0-9]\.[^\s]{2,})/i)[1]; 

    alert(link); 
    }); 
}); 

我已經取得了一些糾正和補充的正則表達式匹配的URL。

DEMO

+0

是的,它似乎工作良好,謝謝! –

相關問題