Detecting URL in Textarea with Regex

Asked

Viewed 77 times

0

Dear, I would like to use the following example (https://www.regextester.com/96504) that marks any link typed, and place in a textarea of my website to mark and warn that links are not allowed. I tested with required Pattern and I couldn’t. I also did the following example but it didn’t work in the textarea:

function isUrl(s) {
    var regexp = (?:(?:https?|ftp):\/\/|\b(?:[a-z\d]+\.))(?:(?:[^\s()<>]+|\((?:[^\s()<>]+|(?:\([^\s()<>]+\)))?\))+(?:\((?:[^\s()<>]+|(?:\(?:[^\s()<>]+\)))?\)|[^\s`!()\[\]{};:'".,<>?«»“”‘’]))?
    return regexp.test(s);
}

I’ve done several other examples but so far I haven’t been able to. Someone could give me a little help to get started. Before anyone else Egative me, I made many examples, it’s been several days since I’m researching about it, and as I can’t put all my tests here so I went straight to the first question and I was negative. Thank you

  • you want to detect or mark?

  • For what I researched here you can not do this directly in Textarea... will have to develop some other solution, because within Textarea is only accepted plain text.

  • Hello Leonardo, I just want to mark for the user to know that he is typing something invalid in the textarea field.

1 answer

1

See if I got it right.... Run there.

// Add your javascript here
$(function(){
  
  function changeColor(parent) {
    var text = parent.text().replace(/\r/g, '');
    var newHTML = "";

    if(/(?:(?:https?|ftp):\/\/|\b(?:[a-z\d]+\.))(?:(?:[^\s()<>]+|\((?:[^\s()<>]+|(?:\([^\s()<>]+\)))?\))+(?:\((?:[^\s()<>]+|(?:\(?:[^\s()<>]+\)))?\)|[^\s`!()\[\]{};:'".,<>?«»“”‘’]))?/.test(text)) {
      newHTML = "<span class='statement'>" + text + "\r</span>";
    } else {
      newHTML = "<span class='other'>" + text + "\r</span>";
    }
    parent.html(newHTML);

    var child = parent.children();
    var range = document.createRange();
    var sel = window.getSelection();
    range.setStart(child[child.length-1], 1);
    range.collapse(true);
    sel.removeAllRanges();
    sel.addRange(range);
    
    parent[0].focus();
  }
  
  changeColor($("#editor"));
  
  $("#editor").on("keydown keyup", function(e){
          changeColor($(this));
  });
});
#editor {
    width: 400px;
    height: 100px;
    padding: 10px;
    background-color: #444;
    color: white;
    font-size: 14px;
    font-family: monospace;
}
  
.statement {
    color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id="editor" contenteditable="true">
</div>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.