skip to Main Content

How can I remove the url from a string? I url might not start with https or http. How can I do this using javascript? I want to prevent people from sending bad urls to my users through the sign up form.

2

Answers


  1. You can use a regular expression that matches the URLs and replace them with an empty string using the .replace() method.

      function removeURLs(text) {
        // Regular expression to match URLs
        const urlRegex = /(b(https?|ftp|file)://[-A-Z0-9+&@#/%?=~_|!:,.;]*[-A-Z0-9+&@#/%=~_|])/ig;
        // Replace URLs with an empty string
        return text.replace(urlRegex, '');
      }
    
    Login or Signup to reply.
  2. You should definitely use regular expressions.

    You can find the answer of how to create a regular expression for URLs here: What is a good regular expression to match a URL?

    Once you have this regular expression, you can do something like this: (And make sure the regular expression has the g modifier flag to cath all instances)

    var myStr = ...;
    const regex = ...;
    myStr.replace(regex, "");
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search