Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove un-parenthesized URLs from a <textarea>

The code within the attached fiddle removes all URLs within a <textarea>.

Is it possible for the code to remove all URLs, except if the URL is inside of a parentheses — e.g. (google.com) — within the <textarea> dynamically?

If possible, I would be appreciate an updated fiddle as I am new to coding.

$(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

like image 709
Dave Avatar asked Nov 04 '15 14:11

Dave


1 Answers

Edit: Please use the following code for the above (string containing single 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, '');
        }
    })
});

Edit: It'll check and remove all the very next urls(multiple urls) coming throughout the string.

       $(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;
                })
            });

Find the updated fiddle for this. Cheers!

like image 53
Akshaya Raghuvanshi Avatar answered Sep 24 '22 14:09

Akshaya Raghuvanshi