URI Regex: Replace http://, https://, ftp:// with empty string if URL valid

27,078

Solution 1

protomatch.test() returns a boolean, not a string.

I think you just want:

var protomatch = /^(https?|ftp):\/\//; // NB: not '.*'
...
var b = url.replace(protomatch, '');

FWIW, your match regexp is completely impenetrable, and almost certainly wrong. It probably doesn't permit internationalised domains, but it's so hard to read that I can't tell for sure.

Solution 2

var b = url.substr(url.indexOf('://')+3);

Solution 3

If you want a more generic approach, like Yuri's, but which will work for more cases:

var b = url.replace(/^.*:\/\//i, '');
Share:
27,078
jQuerybeast
Author by

jQuerybeast

A kid stepping an inch forward every day.

Updated on July 09, 2022

Comments

  • jQuerybeast
    jQuerybeast almost 2 years

    I have a simple URL validator. The url validator works as probably every other validator.

    Now I want, if the URL passed, take the https://, http:// and remove it for var b.

    So what I've done is I made a another Regex which captures https://, http://, ftp:// etc and say if the url passed the long test, get the second test and replace it with empty string.

    Here is what I came up with:

    $("button").on('click', function () {
       var url = $('#in').val();
    
       var match = /^([a-z][a-z0-9\*\-\.]*):\/\/(?:(?:(?:[\w\.\-\+!$&'\(\)*\+,;=]|%[0-9a-f]{2})+:)*(?:[\w\.\-\+%!$&'\(\)*\+,;=]|%[0-9a-f]{2})+@)?(?:(?:[a-z0-9\-\.]|%[0-9a-f]{2})+|(?:\[(?:[0-9a-f]{0,4}:)*(?:[0-9a-f]{0,4})\]))(?::[0-9]+)?(?:[\/|\?](?:[\w#!:\.\?\+=&@!$'~*,;\/\(\)\[\]\-]|%[0-9a-f]{2})*)?$/;
       var protomatch = /^(https?|ftp):\/\/(.*)/;
    
    
       if (match.test(url)) { // IF VALID
          console.log(url + ' is valid');
    
          // if valid replace http, https, ftp etc with empty
          var b = url.replace(protomatch.test(url), '');
          console.log(b)
    
       } else { // IF INVALID
          console.log('not valid')
       }
    
    });
    

    Why this doesn't work?

  • jQuerybeast
    jQuerybeast over 12 years
    Great. I should test protomotach.test() on console. Thank you.
  • Alnitak
    Alnitak over 12 years
    this will remove any URL scheme identifier, not just https, http and ftp.
  • sms
    sms almost 8 years
    what happens if the url itself not contains http or https at some cases.