regx to validate url code example

Example 1: url check regex

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

Example 2: proper regex website url validation

const regex = /^((ftp|http|https):\/\/)?(www.)?(?!.*(ftp|http|https|www.))[a-zA-Z0-9_-]+(\.[a-zA-Z]+)+((\/)[\w#]+)*(\/\w+\?[a-zA-Z0-9_]+=\w+(&[a-zA-Z0-9_]+=\w+)*)?$/gm;
const str = `http://www.sample.com
https://www.sample.com
http://www.sample.com/xyz
www.sample.com
www.sample.com/xyz/#/xyz
sample.com
www.sample.com
mofiz.com
kolim.com
www.murikhao.www.sample.com
http://murihao.www.sample.com
http://www.sample.com/xyz?abc=dkd&p=q&c=2
www.sample.gov.bd
www.sample.com.en
www.sample.vu


`;
let m;

while ((m = regex.exec(str)) !== null) {

    if (m.index === regex.lastIndex) {
        regex.lastIndex++;
    }
    console.log("matched :"+m[0]);
}

Tags:

Misc Example