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.
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.
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.
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.
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/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With