Search code examples
javascriptregexregex-lookaroundsregex-groupregex-greedy

Regex for URL/String - If protocol return false


Trying to create a regex in which the string should not start with http(s)://, http(s)://www. Rest of the string can be anything.

I used this regeg but its return true if we have http://

^(http://www.|https://www.|http://|https://)?[a-z0-9]+([-.]{1}[a-z0-9]+)*.[a-z]{2,5}(:[0-9]{1,5})?(/.*)?$

Another one I tried is

var re = new RegExp("(http|https|ftp)://");
var str = "http://xxxx.com";
var match = re.test(str);
console.log(match);

this one is also returning true.

Demo here

let re = /(http|https|ftp):///;
let url = 'xxxx.xxxx.xxxx'; // this is valid but test returns false
let url2 = 'https://www.xxzx.com/xxx.aspx'; // this should fail as there is https://www in url

console.log(re.test(url)); //
console.log(re.test(url2)); //

Is this possible with regex?


Solution

  • You need to use negative lookahead in your regex to discard strings starting with protocols like http or https or ftp. You can use this regex,

    ^(?!(?:ftp|https?):\/\/(www\.)?).+$
    

    Regex Demo

    JS Demo,

    const arr = ['xxxx.xxxx.xxxx','ftp://www.xxzx.com/xxx.aspx','https://www.xxzx.com/xxx.aspx','http://xxxx.com','https://xxzx.com/xxx.aspx','http://www.xxxx.com']
    
    arr.forEach(s => console.log(s + " --> " + /^(?!(?:ftp|https?):\/\/(www\.)?).+$/.test(s)))