Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check URL contains http using JQuery and RegEx

Tags:

jquery

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.

like image 358
Aadi Avatar asked Oct 06 '11 09:10

Aadi


People also ask

How do you check if the URL contains a given string in jQuery?

How do you check if the URL contains a given string in jQuery? Whether you are using jQuery or JavaScript for your frontend, you can simply use the indexOf() method with the href property using windows. The method indexOf() returns the position (a number) of the first occurrence of a given string.

How do I find the URL contained?

To check if the current URL contains a string in Javascript, you can apply the “test()” method along with the “window. location. href” property for matching the particular string value with the URL or the “toString(). includes()”, or the “indexOf()” method to return the index of the first value in the specified string.

How do you check if a string is present in URL?

HTMLInputElement. checkValidity() method is used to check if a string in <input> element's value attribute is URL . The checkvalidity() method returns true if the value is a proper URL and false if the input is not a proper URL.


1 Answers

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/

like image 124
John Keyes Avatar answered Oct 10 '22 17:10

John Keyes