2015-11-04 43 views
6

連接的小提琴中的代碼將刪除<textarea>中的所有網址。如何從<textarea>中刪除未加圓括號的URL

代碼是否可以刪除所有URL,除非URL位於括號內 - 例如,(google.com) - 動態地在<textarea>之內?

如果可能,我將不勝感激更新的小提琴,因爲我是編碼新手。

$(function() { 
 
    $("#txtarea").keyup(function() { 
 
    console.log(this.value); 
 
    this.value = this.value.replace(/(https?:\/\/)?([\da-z\.-]+)\.([a-z\.]{2,6})([\/\w \.-]*)*\/?/mg, ' '); 
 
    }) 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> 
 

 
<textarea id="txtarea" placeholder="How to stop http being entered into textarea?"></textarea>

Fiddle

+1

您可能想要使用正則表達式,但檢查URL是一個難題(但括號會很容易)。希望這也是一個常見的問題,所以你應該沒有困難找到現有的答案。 – Aaron

+0

_「但是,請保留在括號內的URL,例如(google.com)」_括號字符內部''「[」','「]」'? – guest271314

+0

檢查[this fiddle](http://jsfiddle.net/95b2msaj/10/)。將'(測試http://google.com)粘貼到文本區域中。請注意,如果你輸入'(',那麼'http:// google.com',這個URL將被刪除,因爲它仍然不在'(...)'內。你在找什麼? –

回答

1

編輯:請使用用於上述下面的代碼(包含單個URL字符串)。

$(function(){ 
    var urlmatch = /(https?:\/\/)?([\da-z\.-]+)\.([a-z\.]{2,6})([\/\w \.-]*)*\/?/gm, protomatch = /\((https?:\/\/)?([\da-z\.-]+)\.([a-z\.]{2,6})([\/\w \.-]*)*\/?\)/gm; 
    $("#txtarea").keyup(function(){ 
     if(this.value.match(protomatch) && this.value.charAt(0) == '(' && this.value.charAt(this.value.length-1) == ')'){ 
      this.value = this.value; 
     } 
     else if(this.value.match(urlmatch) && !this.value.match(protomatch) && this.value.charAt(0) != '(' && this.value.charAt(this.value.length-1) != ')'){ 
      this.value = this.value.replace(urlmatch, ''); 
     } 
    }) 
}); 

編輯:它會檢查並刪除所有第二天的URL(多個URL)在整個字符串的到來。

 $(function(){ 
       $("#txtarea").keyup(function(){  
        var urlmatch = /^(https?:\/\/)?([\da-z\.-]+)\.([a-z\.]{2,6})([\/\w \.-]*)*\/?$/, newA = [], a = this.value.split(' '); 
       $.each(a, function (i, j) {//j = $.trim(j); 
       if((j.match(urlmatch) && j.charAt(0) == '(' && j.charAt(j.length-1) == ')') != false) { 
       newA.push(j) 
       } 
       console.log(j, '->', j.match(urlmatch) && j.charAt(0) == '(' && j.charAt(j.length-1) == ')' ) }) 

       var o = newA.join(" ") 
       this.value = o; 
       }) 
      }); 

查找此更新fiddle。乾杯!

+0

當你開始在括號內鍵入你的url:'(在刪除之前我會刪除http:// google.co',然後我可以鍵入關閉的圓括號!抱歉,但這不是一個有效的答案。 – Anonymous0day

+0

我編輯了要修復的代碼 –

+0

唯一的問題是,例如(www.google.com)的括號沒有刪除網址,但是在括號旁邊輸入另一個網址(www.google.com)www.google。 com中,括號內的URL不會被刪除,但括號內的URL是否可以保留,但是,爲了確保URL是不是在支架內從