JS URL regex, allow only urls and empty string

2.1k views Asked by At

I have the following regext:

var regex = /^(http(s)?:\/\/.)?(www\.)?[-a-zA-Z0-9@:%._\+~#=]{2,256}\.[a-z]{2,6}\b([-a-zA-Z0-9@:%_\+.~#?&//=]*)/g;

function test() {
    alert(regex.test(document.getElementById("myinput").value));
}

I want to allow url or empty string. regex solution please
How do I allow empty in this case?
https://jsfiddle.net/6kptovwc/2/
Thanks

3

There are 3 answers

2
Toto On BEST ANSWER

Add an alternation with empty string (I've simplified a bit your regex):

^((?:https?:\/\/)?(?:www\.)?[-a-zA-Z0-9@:%._\+~#=]{2,256}\.[a-z]{2,6}\b[-a-zA-Z0-9@:%_\+.~#?&\/=]*|)$

or

^((?:https?:\/\/)?(?:www\.)?[-\w@:%.+~#=]{2,256}\.[a-z]{2,6}\b[-\w@:%+.~#?&\/=]*|)$

Demo & explanation

1
xdeepakv On

Just add OR(||) condition

function test() {
    const elm = document.getElementById("myinput")
    alert(elm.value === '' || regex.test(elm.value));
}
0
SexyMF On
^$|pattern
var regex = /^$|(http(s)?:\/\/.)?(www\.)?[-a-zA-Z0-9@:%._\+~#=]{2,256}\.[a-z]{2,6}\b([-a-zA-Z0-9@:%_\+.~#?&//=]*)/g;