Aadi
Aadi

Reputation: 7109

How to check URL contains http using JQuery and RegEx

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.

Upvotes: 6

Views: 12531

Answers (1)

John Keyes
John Keyes

Reputation: 5604

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/

Upvotes: 19

Related Questions