-2

I don't know if someone asked this here before, but I just couldn't find what I was looking for exactly. I have a chat app prototype that I'm working on as a way of learning how to make chat apps using React, and i want the app to know if a "certain sent message" is a Url for some website, if so, make it appear as a Url instead of a simple string.

WOUNDEDStevenJones
  • 5,150
  • 6
  • 41
  • 53
TSWcrazy
  • 1
  • 1
  • To clarify - you are trying to detect if a given string is a URL, right? https://stackoverflow.com/questions/5717093/check-if-a-javascript-string-is-a-url – WOUNDEDStevenJones Mar 12 '21 at 21:44

1 Answers1

0

You can try creating a function to validate input and check if it's a URL. Using regex is your best bet I believe.

function validURL(str) {
   var pattern = new RegExp('^(https?:\\/\\/)?'+ // protocol
   '((([a-z\\d]([a-z\\d-]*[a-z\\d])*)\\.)+[a-z]{2,}|'+ // domain name
   '((\\d{1,3}\\.){3}\\d{1,3}))'+ // OR ip (v4) address
   '(\\:\\d+)?(\\/[-a-z\\d%_.~+]*)*'+ // port and path
   '(\\?[;&a-z\\d%_.~+=-]*)?'+ // query string
   '(\\#[-a-z\\d_]*)?$','i'); // fragment locator

   return !!pattern.test(str);
}

Of course you can add remove checks according to your requirements.

Shando
  • 32
  • 9