0

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

SexyMF
  • 10,657
  • 33
  • 102
  • 206

3 Answers3

0

Just add OR(||) condition

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

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

Toto
  • 89,455
  • 62
  • 89
  • 125
  • What do you think about my answer? (I have found a solution) – SexyMF Mar 23 '20 at 16:51
  • @SexyMF: Be aware that your regex is not anchored, it matches `blah blahwww.blah.com$*!§?#~´&²` for example, and the dot in `(http(s)?:\/\/.)` matches any character between the double slash and the url, for example `https://{subdomain.domain.com` another comment is avoid capture groups when yoou don't need to capture, prefer non capture group. Nevertheless if it works for you with all your test cases, that's fine ;) – Toto Mar 23 '20 at 17:12