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.

1

1 Answer 1

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/

Sign up to request clarification or add additional context in comments.

3 Comments

just what i was looking for!
what if the url is something like this ftp://example.com? Try it out
@nmargaritis true, it was an "example" not a solution as the answer pointed out. I've added an updated fiddle that leaves any value with a scheme untouched.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.