Bruno Bruno - 8 months ago 72
Javascript Question

Check if a Javascript string is a url

Is there a way in javascript to check if a string is a url?

RegExes are excluded because the url is most likely written like

; that is to say that it might not have a .com, www or http


A related question with an answer:

Javascript regex URL matching

Or this Regexp from Devshed:

function ValidURL(str) {
  var pattern = new RegExp('^(https?:\/\/)?'+ // protocol
    '((([a-z\d]([a-z\d-]*[a-z\d])*)\.)+[a-z]{2,}|'+ // domain name
    '((\d{1,3}\.){3}\d{1,3}))'+ // OR ip (v4) address
    '(\:\d+)?(\/[-a-z\d%_.~+]*)*'+ // port and path
    '(\?[;&a-z\d%_.~+=-]*)?'+ // query string
    '(\#[-a-z\d_]*)?$','i'); // fragment locater
  if(!pattern.test(str)) {
    alert("Please enter a valid URL.");
    return false;
  } else {
    return true;