Colt Clint
Colt Clint

Reputation: 1

If else does not works properly

I have a Function (with help of other user of stackoverflow), but only the first if statement works, the second not. I want to take advantage of this code to get both: http and https followed or not by www

function formatURL() {
  var url = document.getElementsByName("URL")[0];
  var formattedURL = document.getElementsByName("formattedURL")[0];
  url = url.value;
  if (url.substr(0, 0) === "") // with our without www
  {
    formattedURL.value = "https://" + url;
    return;
  } else
  {
    formattedURL.value = "http://" + url;
    return;
  }
}
formattedURL.value = url;
}

Upvotes: -1

Views: 47

Answers (1)

Sunny Patel
Sunny Patel

Reputation: 8077

You're running into this issue because url.substr(0,0) will always be an empty string "" for any string value of url (your if statement is always true).

Not sure what exactly you're trying to compare url.substr against because we don't have all the possible inputs you give to your <URL/> elements. Otherwise, I could have an actual fix for you.

Upvotes: 2

Related Questions