6

How can I check and add http (if it does not exist) in given url using jQuery and RegEx?

I tried the following:

jQuery("#text_box_url").blur(function() {
    if (jQuery(this).val()) {
        if(jQuery(this).val().match(/~^(?:f|ht)tps?:/))
            jQuery(this).val("http://"+jQuery(this).val());
    }
});

Thanks in advance.

John Keyes
  • 5,479
  • 1
  • 29
  • 48
Aadi
  • 6,959
  • 28
  • 100
  • 145
  • duplicate of: http://stackoverflow.com/questions/282444/how-can-i-use-javascript-on-the-client-side-to-detect-if-the-page-was-encrypted? – JMax Oct 06 '11 at 10:00

1 Answers1

19

Working example here: http://jsfiddle.net/jkeyes/dYbfY/2/

$("#text_box_url").blur(function() {
  var input = $(this);
  var val = input.val();
  if (val && !val.match(/^http([s]?):\/\/.*/)) {
    input.val('http://' + val);
  }
});

Update a solution that leaves all values with a scheme untouched: http://jsfiddle.net/jkeyes/c6akr9y2/

John Keyes
  • 5,479
  • 1
  • 29
  • 48