2015-11-04 67 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是不是在支架内从